Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize model and collection in backbone

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?

like image 206
Andreas Köberle Avatar asked Oct 02 '11 21:10

Andreas Köberle


People also ask

What is a model Backbone?

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.

What is collections in Backbone JS?

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.

Are the array of models that are created inside the collection?

Initialize function is defined to create a model instance. 4. It specifies the array of models which are created inside of the collection.


2 Answers

Yes, you're on the right track. You simply have to define three things:

  1. A Model for your order object
  2. A Model for the order_item object
  3. A Collection for order_items

Remember 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_items 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!

like image 135
umar Avatar answered Oct 04 '22 12:10

umar


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

like image 33
Derick Bailey Avatar answered Oct 04 '22 11:10

Derick Bailey