简体   繁体   中英

backbone.js correct way to update model when view changed

What is a correct way to update model when view changed. Is it need to do in a view or in some other place like controller or so?

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. 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. The second question - should View1 or Model1 know about collection, and if yes - how it should be done?

There is interesting approach of MVC theory, applied to MVC... Look here for more explaination what is controller in Backbone

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

written by @derick-bailey

In general summary, Bailey says that there are no controllers in Backbone. So, I personally think, that every model updates should take place in the View, associated with that 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.

In your example

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

And when View1 changes model1, then model1 triggers an event to View2.collection, which you can listen.

Controllers talk to models, so yes: the correct way to update your model when the view changed is through your controller

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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