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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:09:12  来源:igfitidea点击:

backbone.js View determine which attribute of model is change

javascriptbackbone.jsbackbone-model

提问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 changedAttributesfunction 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 hasChangedfunction

或检查特定属性是否已更改使用该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");

回答by Andreas K?berle

You can bind to change:nameif 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