5
votes

How can I access the view from a model in backbone.js.

I would love to re-render the view on model.change().

3

3 Answers

11
votes

Adding views to the model's attribute is a no-no.

Why would you need to access the view from model on its change?

In your view, simply bind:

this.model.bind('change', this.modelChanged, this) // (event, function, context)

and from now on, when your model changes, your view's modelChanged method will be called automatically.


in version >0.9, the proper syntax will be like this in the view.

this.model.on('change', this.modelChanged, this) // (event, function, context)
1
votes

You may use one of two bindings:

this.model.bind('change', this.modelChanged)

this.model.bind('refresh', this.modelRefreshed)

Check the docs to see the differences.

1
votes

There's another potential snafu to adding a view property to the model. It's possible that a model might be represented by multiple views. When this happens you'd have to change the view property to (an array) views. That's harry coding. I started off doing just this thing and realized my faux pas once I saw that multiple views could be involved. I realized this was just another way of handling the publisher-subscriber pattern.

Others have been happy to have the model and view reference the other as a means of two-way communication. Gravel-Niquet does so in his Todos sample app. Lerner suggests this in his June 2011 Linux Journal article on Backbone.js. A matter of preference, perhaps, but I am with with pawlik. Stick to events; that's what they're for.