Backbone.js View a definition of which attribute of a model is changing.

How to find out which attribute of the view model is changed in the rendering function? (In the rendering function, โ€œeโ€ is a model, but I only need the attribute that has been changed.) I need to know this to find out which template to use. Or is there another way to do this?

window.Person = Backbone.Model.extend({}); window.Njerzit = Backbone.Collection.extend({ model: Person, url: '/Home/Njerzit' }); window.PersonView = Backbone.View.extend({ tagName: 'span', initialize: function () { _.bindAll(this, 'render'); this.model.bind('change', this.render); }, render: function (e) { //if model name is changed, I need to render another template this.template = _.template($('#PersonTemplate').html()); var renderContent = this.template(this.model.toJSON()); $(this.el).html(renderContent); return this; } }); 
+6
source share
2 answers

I believe the changedAttributes function is what you are looking for

changedAttributesmodel.changedAttributes ([attributes])
Retrieve the hash of only the modified model attributes. Optionally, a hash of the external attribute hashes can be passed by returning attributes in that hash that are different from the model. This can be used for which parts of the view should be updated or what calls are needed to synchronize changes with the server.

or to check if a particular attribute has changed, use the hasChanged function

hasChangedmodel.hasChanged ([attribute])
Has the model changed since the last โ€œchangeโ€ event? If the attribute is passed, returns true if this specific attribute has changed.

 var nameChanged = this.model.hasChanged("name"); 
+14
source

You can bind to change:name if you only want to notify if the name has changed: http://documentcloud.github.com/backbone/#Model-set

+12
source

Source: https://habr.com/ru/post/904631/


All Articles