简体   繁体   English

backbone.js 视图更改时更新 model 的正确方法

[英]backbone.js correct way to update model when view changed

What is a correct way to update model when view changed.视图更改时更新 model 的正确方法是什么。 Is it need to do in a view or in some other place like controller or so?是否需要在视图中或其他地方(如 controller 左右)进行操作?

for example I have a model (model1) and some view (View1) associated with this model. I need to update model when I change some fields on the view.例如,我有一个 model (model1) 和一些与此 model 关联的视图 (View1)。当我更改视图上的某些字段时,我需要更新 model。 Which is correct way to do that?哪种方法是正确的?

Also, I have a collection of that models associated with another view (View2), and i need to put model (model1) to that collection.另外,我有一个与另一个视图 (View2) 关联的模型集合,我需要将 model (model1) 放入该集合。 The second question - should View1 or Model1 know about collection, and if yes - how it should be done?第二个问题 - View1 或 Model1 是否应该知道集合,如果是 - 应该如何完成?

There is interesting approach of MVC theory, applied to MVC... Look here for more explaination what is controller in Backbone有一种有趣的 MVC 理论方法,适用于 MVC ...在此处查看更多解释 Backbone 中的 controller 是什么

http://lostechies.com/derickbailey/2011/12/23/backbone.js-is-not-an-mvc-framework/ http://lostechies.com/derickbailey/2011/12/23/backbone.js-is-not-an-mvc-framework/

written by @derick-bailey由@derick-bailey 撰写

In general summary, Bailey says that there are no controllers in Backbone.总的来说,Bailey 说 Backbone 中没有控制器。 So, I personally think, that every model updates should take place in the View, associated with that model.所以,我个人认为,每个 model 更新都应该在与 model 关联的视图中进行。

Every model in Backbone, when is added to a collection ( or collections ) and is updated triggers an event in the collection(s) it belongs, so you should listen for that event in your view. Backbone 中的每个 model 被添加到集合(或 collections )并更新时会触发其所属集合中的事件,因此您应该在视图中监听该事件。

In your example在你的例子中

  • View1.collection = [model1]; View1.collection = [model1];
  • View2.collection = [model1, model2, model3]; View2.collection = [model1, model2, model3];

And when View1 changes model1, then model1 triggers an event to View2.collection, which you can listen.而当View1改变model1时,则model1触发一个事件给View2.collection,你可以监听。

Controllers talk to models, so yes: the correct way to update your model when the view changed is through your controller控制器与模型对话,所以是的:当视图更改时更新 model 的正确方法是通过您的 controller

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

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