Friday, 27 September 2013

Backbone.js How to retrieve a model in a nested collection?

Backbone.js How to retrieve a model in a nested collection?

I have a PizzaType model that has a nested collection of Pizzas. The
Pizzas Collection is listed based on the Pizza Type. I would like to be
able to click on a pizza in the pizzas collection and display its
attributes.
What would be the best way to set the url params dynamically? The url does
not need a route to navigate to for bookmarking and sharing, just to
retrieve the specific resource.
I have it so that if someone wants to view the pizza type the url is
pizza_type/:id :id is the id belonging to the Pizza Type (parent model)
I currently have it so if a pizza is clicked on in the Pizzas Collection
(that belongs to the Pizza Type Model), the path to the pizza resource is
not followed; just a region on the page is updated. The url path is needed
so jQuery can get the resource to update that region. The url to the pizza
is pizza_types/:pizza_type_id/pizzas/:id Here, the :id is the id belonging
to the Pizza Model, and the :pizza_type_id is the foreign key that members
of the Pizzas Collection share to group them into the collection, that
belong to the Pizzas Type Model.
When I click on the pizza (id = 3), I get "NetworkError: 404 Not Found -
http://localhost:3000/pizza_types/3/pizzas"
Here is the Model and Collection Code:
@Pizzeria.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.PizzaType extends Backbone.Model
urlRoot: "pizza_types/"
# creates the nested collection
initialize: ->
@pizzas = new Entities.PizzasCollection
@pizzas.url = @urlRoot + @id + '/pizzas'
@pizzas.fetch
reset: true
parse: (response) ->
response
class Entities.PizzaTypesCollection extends Backbone.Collection
model: Entities.PizzaType
url: 'pizza_types'
parse: (response) ->
response
# Is there a way to pass in a :pizza_type_id and :id params to pass to
the url() so
# that the specific pizza model can be retrieved from the collection?
class Entities.Pizza extends Backbone.Model
url: -> "pizza_types/" + 2 + "/pizzas/" + 4 # <-- Hard coded works,
but how to set the params dynamically?
parse: (data) ->
data
class Entities.PizzasCollection extends Backbone.Collection
model: Entities.Pizza
url: 'pizzas'
parse: (data) ->
data
Any suggestions? Is this the proper way, I tried to do this as well:
class Entities.Pizza extends Backbone.Model
urlRoot: -> "pizza_types"
# I thought I could pass these params in and fetch the correct
pizza model, but not working.
fetch
pizza_type_id: pizza_type_id
id: id
reset: true
parse: (data) ->
data
PizzaType Attributes with example data:
PizzaType: {
id: 2,
name: "Gourmet",
pizzas: [
0: {
id: 4,
pizza_type_id: 2
name: "gourmet pizza 1"
},
1: {
id: 5,
pizza_type_id: 2,
name: "gourmet pizza 2"
}
]

No comments:

Post a Comment