3

I have a Backbone Model and am doing some validation when the setter is called. Instead of returning an error, I want to overwrite the value. How do I do this?

myObj = Backbone.Model.extend({
  // Attributes
  x: function() { },
  y: function() { },

      // Validation
      validate: function(atr) {

            // Checking for number
            var numberRegex = /^\d+$/;

            if(!numberRegex.test(atr.x)) // not number
                  atr.x = 'NA'; // Trying to set x to "NA"
      }
});

Thanks!

4

1 回答 1

1

您在 validate 函数中收到的 atr 是模型属性的副本。因此,更改它不会更改模型中的属性。在 validate call 中设置属性this.set('x','NA',{silent:true});

于 2012-11-08T07:33:00.367 回答