取消设置以相同子字符串开头的Backbone.js模型的所有属性

时间:2013-02-25 20:11:46

标签: javascript backbone.js model underscore.js

我想取消设置Backbone.js模型的所有属性,这些属性以相同的子字符串开头,如:

logo_id
logo_width
logo_height

我想做点什么:

model.unsetAllStartsWith('logo');

代码如下:

_.extend(Backbone.Model, {
    unsetAllStartsWith : function(str){
        // something with this.toJSON() ?
    }
});

我对模型和toJSON感到困惑。另外,这是扩展Backbone模型类的正确方法吗?

3 个答案:

答案 0 :(得分:4)

Backbone.Model内置了一个extend方法,所以你可以这样做:

var MyModel = Backbone.Model.extend({
    unsetAllStartsWith: function(str){
       // get clone of attributes to iterate over
       var attrs = _.clone(this.attributes);
       _.each(attrs, function(val, key){
              if(key.indexOf(str) == 0){
                  this.unset(key);
              }
           }, this);
    }
});

var model = new MyModel({logo_width: 100, logo_height: 200});
model.unsetAllStartsWith('logo');

答案 1 :(得分:2)

试一试。

 unsetAllStartsWith : function(str){
        var $this = this
        var properties = Object.keys($this.toJSON());
        _.each(properties, function(property) {
            var regex = new RegExp('^'+ str, 'gi')
            if(property.match(regex))
               $this.unset(property)        
        }

      }

}

答案 2 :(得分:1)

这里添加方法(jsfiddle)略有不同:

Backbone.Model.prototype.unsetAllStartsWith = function(prefix) {
    var that = this;
    _.each(this.attributes, function(attrVal, attrName) {
      if (attrName.slice(0,prefix.length) === prefix) {
          that.unset(attrName);
      }
  })
};

像这样使用:

var MyModel = Backbone.Model.extend({
    defaults: {
        'foo_first': 'bar',
        'foo_second': 'bar2',
        'different': 'bar3'
    }
});

var testModel = new MyModel();
testModel.unsetAllStartsWith('foo');