How can I access the view from a model in backbone.js.
I would love to re-render the view on model.change().
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)
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.