31

So far all tests and tutorials i've been trying, to get the structure in my head, show me that a view is bound to 1 model.

lets say i have a small app to store and manage contact details (an address book) i have multiple users that can login and they each have their own collection of contacts.

the user detail view would be bound to the user model same goes for contacts

but say i would like to show a grid combining those two X axis showing all contacts in the app Y axis showing all users,

how does this work? do i need to create a new model for this, to bind to a new view?

you get the idea, its just a theoretical example i am not building that app but its to get the idea of having a view combining multiple models

Sander
  • 13,301
  • 15
  • 72
  • 97
  • To access the two models from within the view, see http://stackoverflow.com/questions/7734559/backbone-js-passing-2-models-to-1-view – storm_m2138 Sep 24 '12 at 20:45

2 Answers2

50

In that case, I'd consider a dynamic model with both of your sub-models. In your route handler, you could do something like this:

var model = new Backbone.Model();
model.set({contacts: new ContactsModel(), users: new UsersModel()});
var view = new GridView({model: model});

Of course, there is nothing stopping you from passing in the models separately:

var contacts = new ContactsModel();
var users = new UsersModel();
var view = new GridView({model: contacts, users: users})

I still prefer the composite approach of the first because it doesn't conflate what the model is.

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
  • thanks for the info, i already knew i could do something like the second approach, but as you say, I too would find it odd as it would define the contacts as the model, while the users would be some extra information only... I didn't know of this dynamic model structure, I would have to create and store a whole new model inbetween my real entities. thanks for the insight! – Sander Sep 12 '11 at 11:25
  • 5
    How to handle model.fetch() in this case? Your model doesn't have url. – Stanislav Ostapenko Jan 27 '15 at 18:38
7

You can also consider merging both models, if you are sure they dont use the same parameters.

var modelA = new myModel({ color: "blue" });
var modelB = new otherModel({ age: 35 });

var superModel = new Backbone.Model();
superModel.set(modelA);
superModel.set(modelB);

console.log("color:", superModel.get("color"));
console.log("age:", superModel.get("age"));

take a look at Backbone.Model.extend() as well

Adam Bowen
  • 656
  • 8
  • 8
ximonn
  • 79
  • 1
  • 1