如何区分骨干中模型/集合属性的更改和删除?

时间:2014-08-19 08:57:26

标签: backbone.js

我想知道在主干中是否有任何事件触发,以区分属性值的更改和删除主干模型或集合中的属性

2 个答案:

答案 0 :(得分:1)

不,在模型属性上调用unset只会触发change event。如果你需要有一个不同的事件要挂钩,我建议在模型中添加一个方法来包装未设置的调用并触发自定义事件:

var MyModel = Backbone.Model.extend({
  removeAttribute: function (attr) {
    this.unset('attr', { silent: true });
    this.trigger('attributeRemoved');
  }
});

var newModel = new MyModel({ first: 'foo', second: 'bar' });
newModel.removeAttribute('first');

答案 1 :(得分:1)

setunset都会触发'change'事件。来自Backbone文档:

  • 设置

      

    在模型上设置属性的哈希值(一个或多个)。如果有的话   属性改变模型的状态,“改变”事件将是   触发了模型。特定属性的更改事件也是   触发,你也可以绑定到那些,例如:   更改:标题和更改:内容。您也可以传递个人密钥   和价值

  • <强>取消设置

      

    通过从内部属性哈希中删除属性来删除该属性。   除非作为选项传递静音,否则会触发“更改”事件。

如果您查看backbone source code,您会看到以下内容未设置:

// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
  return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},

修改

您可以创建自己的unset函数来替换Backbone.Model中的现有函数,您可以在其中触发您可能需要的任何新事件:

var FooModel = Backbone.Model.extend({
    unset: function(attr, options) {
        options || (options = {});

        //Call unset in Backbone.Model, set silent option also if suppressChangeEvent was set
        var silent = options.silent;
        options.silent = silent || options.suppressChangeEvent;
        var res = Backbone.Model.prototype.unset.apply(this, arguments);

        //trigger unset events if not silent and the attribute was removed
        if (attr == null || silent || !this.hasChanged(attr)) return res;            
        this.trigger('unset:' + attr, this, this._previousAttributes[attr], options);
        this.trigger('unset', this, options);            
        return res;
    }
});

我创建了this fiddle,因此您可以看到这个想法。如果您使用以下代码进行测试:

var myModel = new FooModel({key1 : 1, key2: "foo", key3: "a"});
myModel.on("change", function(){ console.log("change triggered"); });
myModel.on("change:key1", function(){ console.log("change for key1 triggered"); });
myModel.on("change:key2", function(){ console.log("change for key2 triggered"); });
myModel.on("unset", function(){ console.log("unset triggered"); });
myModel.on("unset:key1", function(){ console.log("unset for key1 triggered"); });
myModel.on("unset:key2", function(){ console.log("unset for key2 triggered"); });

myModel.unset("key1");
myModel.unset("key2", {suppressChangeEvent: true});
myModel.unset("key3", {silent: true});
myModel.unset("key5");

您将在控制台中看到以下输出(针对key1触发的所有事件,仅针对key2触发的未设置事件,如果无声或属性不存在,则为none):

change for key1 triggered
change triggered
unset for key1 triggered
unset triggered
unset for key2 triggered
unset triggered