在 Backbone 中侦听和修改模型属性的正确方法是什么.js

What is the correct way in Backbone.js to listen and modify a model property

本文关键字:方法 js 是什么 属性 模型 Backbone 修改      更新时间:2023-09-26

我有一个视图附加到一个属性为"title"的模型。我希望每次设置时都能修剪值(出于某种晦涩的原因,我不想在服务器端执行此操作)。在我的模型中,我尝试了这个:

this.on('change:title', this.trimName);
//... later on
trimName: function(){
    console.log('triggered');
    this.set({'title':$.trim(this.get('title'))}, {silent:true});
}

但这会触发无限递归。(另外,递归不会发生在jsfiddle上,为什么?

提前谢谢。

使模型进行修整:重写set方法并在修整后运行Backbone.Modelset方法。

请注意,这并没有完全清除以处理对象文字,您需要 自己实现。 这将适用于key, value, option参数。查看set 示例 Backbone 源代码中的方法:http://backbonejs.org/backbone.js

set: function(key, value, options) {
      var attrs;
      // Handle both `"key", value` and `{key: value}` -style arguments.
      if (_.isObject(key) || key == null) {
        attrs = key;
        options = value;
      } else {
        attrs = {};
        attrs[key] = value;
      }
      options = options || {};
      if ( options.trim ) {
          attrs[key] = $.trim( attrs[key] );
      }
      // do any other custom property changes here
      Backbone.Model.prototype.set.call( this, attrs, options ); 
}