chenglou
chenglou

Reputation: 3640

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

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.

Upvotes: 0

Views: 2027

Answers (1)

uadnal
uadnal

Reputation: 11445

Make the model do the trimming: Override the set method and run Backbone.Model's set method after you trim.

Note that this is not totally flushed out to handle an object literal, you'll need to implement that yourself. This will work for key, value, option parameters. View the set method in Backbone's source code for an example: 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 ); 
}

Upvotes: 2

Related Questions