简体   繁体   English

主干中的模型更改渲染

[英]Model change rendering in Backbone

Most Backbone tutorials and examples I've come across suggest something like this for your models: 我遇到的大多数Backbone教程和示例都为您的模型提出了类似的建议:

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. 在我的特定情况下,我正在为模型创建一个view,它是一个form ,并且字段与模型属性相关联。 When the user updates a field on the form , the model should also be updated. 当用户更新form上的字段时,还应该更新模型。 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. 因此,现在无论何时我更改form上的值,都将重绘我的视图。 This is both inefficient, and causing lots of frustrating bugs (like focus being lost). 这既效率低下,又会导致许多令人沮丧的错误(例如失去焦点)。

How is this problem normally handled? 通常如何处理此问题?

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

When you don't want your model change to trigger your view's rendering, use {silent: true} . 如果您不想更改模型来触发视图的呈现,请使用{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). 从Backbone的最新版本开始,这将完全使更改静音(以前只是关闭,直到下一个非静默更改为止)。 So when the change to your model comes from some user input, use the silent flag. 因此,当模型的更改来自某些用户输入时,请使用silent标志。

如果您想在不触发变更事件事件的情况下更新模型,可以通过调用来进行,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM