benhowdle89
benhowdle89

Reputation: 37464

Backbone - handing two collections to one view

I have a Backbone view, for example, an Edit Profile view, where I'd hand the view my User model instance. However, I'd like, for example, to allow the user to select their favourite social network from a select dropdown. Now, this list of social networks is populated by them in another area of the application.

My question is, 1. what's the best way to store these social networks? A model for each, so a collection of Social networks? and 2. do I then pass a collection (social networks) and a model (the User) to my Edit Profile view?

Is this the best way?

Upvotes: 1

Views: 2256

Answers (1)

jakee
jakee

Reputation: 18566

Basically you can use the initialize -function to do this kind of stuff. You can pass the other as the model or collection and the other just as some parameter, you just have to save a reference to it. Also you can give a view a model AND a collection.

var EditProfileView = Backbone.View.extend({
  initialize: function(options) {
    this.user = options.user:
    // or do this
    this.socialNetworks = options.socialNetworks; 
  }
});

// when creating an instance do
var foo = new EditProfileView({user: someUser, collection: socialNetworks});
// or
var foo = new EditProfileView({model: someUser, socialNetworks: socialNetworks});
// also this will work as well
var foo = new EditProfileView({model: someUser, collection:socialNetWorks});

Also, if you don't want to assign it, you can just do

var foo = new EditProfileView({user: someUser, socialNetworks: socialNetworks});
// the options given to a view on initialization 
// are saved to an options property in the view
// so the following should hold true
foo.options.user === someUser;
foo.options.socialNetworks === socialNetworks;

Hope this helps!

Upvotes: 8

Related Questions