5

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

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

3 Answers 3

11

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the teaching :) If I do your code I get: Uncaught TypeError: Object [object DOMWindow] has no method 'change'. At ichbinadrian.ch/map/stackoverflow you can have a look at the code. I'm prototyping and learning :)
Try to debug what this.view returns. It's a large piece of code and it would be very helpful if you could narrow it to the essential parts.
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.