0

I have a view attached to a model with an attribute "title". I want to be able to trim the value each time it is set (for some obscure reason, I don't want to do this on server-side). In my model I tried this:

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

but this triggers an infinite recursion. (Also, the recursion doesn't happen on jsfiddle, why?).

Thanks in advance.

4

1 に答える 1

2

モデルにトリミングを行わせる: メソッドをオーバーライドし、トリミング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 ); 
}
于 2012-07-03T17:50:17.457 に答える