MonkeyBonkey
MonkeyBonkey

Reputation: 47861

Does backbone.js do any implicit associating a model with a view

Looking at some backbonejs examples on codeschoo.com, I don't see any explicit associations between views and their models. How does a view know what model it should be associated with? Is it by convention, e.g. TodoView assumes that this.model is of type Todo?

To explicitly set the model to the view, is it just a matter of passing in the model in the constructor?

Upvotes: 1

Views: 142

Answers (1)

JMM
JMM

Reputation: 26787

If you pass a model property to a view constructor, it will set that directly as a property of the view instance, e.g. view.model. That's the case for a select group of other properties as well. Beyond those, properties passed to view constructors are set in view.options.

So yes, you can do this:

var view = new Backbone.View( {

  model : new Backbone.Model

} );

Or change a an existing view instance's model any time by assigning to model:

view.model = new Backbone.Model;

Some people set references to views in models (e.g. model.view), but so far I've avoided that.

http://backbonejs.org/#View-constructor

When creating a new View, the options you pass are attached to the view as this.options...There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes.

Upvotes: 2

Related Questions