0
votes

Most Backbone tutorials and examples I've come across suggest something like this for your models:

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

In my particular case, I'm creating a view for my model that is a form, and the fields are tied to model properties. When the user updates a field on the form, the model should also be updated. This has not been a problem, as I have events bound to the fields that fire off the appropriate code to update my model.

However, the problem I'm running across is that I also want the view to update when the model does (as in the above mentioned ubiquitous change event binding). This is causing the view to re-render itself any time a field is updated, because the underlying model is changing. So now any time I change a value on the form, my view is being redrawn. This is both inefficient, and causing lots of frustrating bugs (like focus being lost).

How is this problem normally handled?

2
Don't render the view on the model change. Render it when you want it using this.render - pvnarula
@pvnarula: That would mean that my view would not update if the model changes via anything outside the view, though. Are you suggested that that should never happen? - FtDRbwLXw6
As an aside, the preferred way to listen for model changes in a view is this.listenTo(this.model, 'change', this.render) as that will not leave a memory leak when the view is removed. - Andrew
@Andrew: Thanks for that tip; I will update my code. - FtDRbwLXw6

2 Answers

3
votes

http://backbonejs.org/#Events-catalog

When you don't want your model change to trigger your view's rendering, use {silent: true}. As of the last version of Backbone, this will completely silence the change (it was previously just shut until the next non-silent change). So when the change to your model comes from some user input, use the silent flag.

1
votes

If you would like to update a model without firing a change event event you can do so by calling,

this.model.set('val', newval, {silent:true});