I have a JSON response with the following structure:
{
id: 1,
status: 0,
created_at: "Y:m:d H:m:s",
updated_at "Y:m:d H:m:s)",
order_items: [items]
}
Could I make a collection with it? The ID, status etc. are just metadata. Or should I create new ItemsCollection
for the items array? Also will I get notified when an item changed?
Model. Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.
Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.
Initialize function is defined to create a model instance. 4. It specifies the array of models which are created inside of the collection.
Yes, you're on the right track. You simply have to define three things:
Model
for your order
objectModel
for the order_item
objectCollection
for order_item
sRemember that every Model
is responsible for its own validation, so you need to write a validate function for it.
Then, every time you parse your JSON, in your item's parse
method, you need to convert the order_item
s to a backbone Collection
using something like:
parse: function(response) {
if (!_.isNull(response) && !_.isNull(response.orderitems)) {
response.orderitems = new OrderItems(response.orderitems);
}
return response;
}
Once you've done this, everything should work as-intended!
you can do all of that, but you have to do it yourself or with a plugin. chances are, the code you end up writing will be similar to what's available in the Backbone.Relational plugin:
http://github.com/PaulUithol/Backbone-relational
i recommend using that plugin instead of rolling the code yourself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With