Search code examples
javascriptbackbone.jsmodel-associationsbackbone-relationalbackbone.js-collections

How do I use & access a Backbone.js Collection as property/attribute in a Model?


I'm new to Backbone (still stuck in Ruby on Rails mode) and am a bit confused about how to add a Collection to a Model as a property/attribute (is "attribute" the correct term?).

For example, I have a Model named current_plan, and a variable named json_dump that was returned from the server that includes an array of participants. I want it to have an attribute named participants (which is a Collection of participants), fill it from the json_dump.participants variable, and be able to use code like `current_plan.participants.where({first_name: "Dan"}).

Here are some snippets of my initialize function:

var current_plan = new Plan();

current_plan.set({attribute: val} ...other attributes... );
current_plan.participants = new Backbone.Collection(json_dump.participants);

But that forces me to access regular attributes like: current_plan.attributes.attribute. Also, I can see that there is correct data in the current_plan.attributes.participants.models, but I can't figure out how to use any of the Collection methods on current_plan.

Clearly I don't understand what's going on, and why there are so many extra layers involved. The Backbone docs seem a little sparse, and I haven't been able to find anything on SO or Google searches that match what I want to do. If there's another question or tutorial out there that explains this, I'd greatly appreciate someone pointing me that way. I also saw the Backbone Relational project which seems like it may be what I need, but I'd prefer not to add more complication to Backbone until I understand the basics.

Thanks for any help you can provide to help a new Backbone user out!


Solution

  • the backbone framework doesn't have a official way to handle relationships between models and collections i think, and i don't use backbone relational, but i have multiple relationships in my backbone collections/models. when i am defining a relationship model with a collection i use it as a property of the model object, not a backbone atribute, so:

    var current_plan = new Backbone.Model(); //or backbone model extended 
    current_plan.participants = new Backbone.Collection(json_dump.participants);
    

    then as @andrew-hubbs says you should always use the backbone api to deal with models and collections attributes to have consistency in your code along with backbone versions for example. then you can access/set the model properties like this

    current_plan.get('property'); 
    participant = current_plan.participants.get(1);
    participant.get('property');
    participant.set('name', 'bob');