Real Dreams
Real Dreams

Reputation: 18010

Using a literal object as a Backbone.Model

I need to send a literal object to a view. Is there any better alternative to the following code:

var model= (new (Backbone.Model)).set({'foo':1,'bar':3})

Upvotes: 0

Views: 90

Answers (2)

seebiscuit
seebiscuit

Reputation: 5053

Yes, if you're just passing in some variables that are not relevant to the view data, then you should not be passing in a model. I can think of two other, more performant, ways to get data into your view.

Passing in data on instantiation

Every view will take parameter passed into the View constructor and hand them off the the view initialize (Backbone does a bit more with passed in parameters, but they all end up in initialize). Let me show you a trivial example.

var MyView = Backbone.View.extend({
  initialize: function(options) {
    // All the parameter you pass into the view construct with will be
    // in the initialize options

    // Attach options to the view so you can access your options
    // from all view properties (bound to the view)
    this.options = options || {};
  }
}

Now get your object literal into your view:

var aView = new MyView({'foo':1,'bar':3});
aView.options.foo; // 1
aView.options.bar; // 3

Making data available after instantiation

If you want to merge an object after instantiation, then simply use _.extend:

_.extend(aView, {'foo':1,'bar':3});
aView.foo; // 1
aView.bar; // 3

Upvotes: 0

ChinKang
ChinKang

Reputation: 4342

just simply

var model = new Backbone.Model({'foo':1,'bar':3})

Upvotes: 1

Related Questions