Leahcim
Leahcim

Reputation: 41929

backbone: relationship between models and views

in one of the Views (View A) of a backbone app I am looking at (which has multiple models), it has this line in its initializer

  this.model.bind('change', this.setText, this);

In another View (View B), it has this line in its initializer

this.model.bind('change', this.render, this);

However, nowhere in either View does it indicate which Model it is connected to. i.e. there's no declaration of what 'model' is. Does that mean that any Model that triggers a 'change', for example, will trigger this.setText in View A as well as (at the same time) this.render in View B?

Upvotes: 0

Views: 442

Answers (1)

mu is too short
mu is too short

Reputation: 434665

From the fine manual:

constructor / initialize new View([options])

[...] There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes.

So when you instantiate a view with this:

var v = new SomeView({ model: m });

Backbone will automatically set this.model to m inside v and this will be done before initialize is called. Look for the constructor calls for the views that have those bind calls, you should see the model supplied when the views are instantiated.

Does that mean that any Model that triggers a 'change', for example, will trigger this.setText in View A as well as (at the same time) this.render in View B?

No, each view (in this case) will have its own model that is supplied when the view is instantiated, the events will come from only that model.

Upvotes: 4

Related Questions