javascript backbone.js 视图确定模型的哪个属性发生变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8661631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
backbone.js View determine which attribute of model is change
提问by Florim Maxhuni
How can I know which attribute of the view model is changed in the render function? (In the render function, "e" is the model, but I need only the attribute which is changed.) I need to know this to know which template to use. Or is there another method to do this?
如何知道渲染函数中更改了视图模型的哪个属性?(在渲染函数中,“e”是模型,但我只需要更改的属性。)我需要知道这一点才能知道要使用哪个模板。或者有另一种方法可以做到这一点?
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;
}
});
回答by soldier.moth
I believe the changedAttributes
function is what you're looking for
我相信这个changedAttributes
功能就是你要找的
changedAttributesmodel.changedAttributes([attributes])
Retrieve a hash of only the model's attributes that have changed. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.
changedAttributesmodel.changedAttributes([attributes])
仅检索已更改的模型属性的哈希值。可选地,可以传入外部属性散列,返回该散列中与模型不同的属性。这可用于确定应更新视图的哪些部分,或需要进行哪些调用以将更改同步到服务器。
or to check if a specific attribute has changed use the hasChanged
function
或检查特定属性是否已更改使用该hasChanged
功能
hasChangedmodel.hasChanged([attribute])
Has the model changed since the last "change" event? If an attribute is passed, returns true if that specific attribute has changed.
hasChangedmodel.hasChanged([attribute])
自上次“更改”事件以来,模型是否发生了变化?如果传递了一个属性,如果该特定属性已更改,则返回 true。
var nameChanged = this.model.hasChanged("name");
- From Backbone Docs
回答by Andreas K?berle
You can bind to change:name
if you only want to notify if the name has changed: http://documentcloud.github.com/backbone/#Model-set
change:name
如果您只想通知名称已更改,则可以绑定到:http: //documentcloud.github.com/backbone/#Model-set