For some strange reason my model is still setting attributes when I return a string in the models validation. Here is my code validation code:
Model = Backbone.Model.extend({
validate: function( attributes ){
var tax = attributes.tax;
if(tax.amount < 0.0 || typeof tax.amount !== "number"){
return "The tax amount cannot be negative and must be a number.";
}
},
defaults: {
"tax": {
"amount": 100
}
},
setTax: function(amount){
var tax = this.get("tax");
tax.amount = amount;
this.set("tax", tax);
}
})
I then have the model listen for the error event and console log it through:
model = new Model();
View = Backbone.View.extend({
initialize: function(){
this.model.on('error', function(model, error){
console.log("ERROR: " + error);
})
}
});
view = new View({model: model});
view.model.setTax(-100);
The console log is being printed, but for some reason the model is still setting the property. Is there anything I need to return to not have the model set the property? According to the Backbone.js docks if you return anything from the validation then it is suppose to not set the property. I’m using Backbone.js version 0.9.2
Your problem is right here:
The
getmethod basically doesreturn this.attributes[attr]and thetaxattribute is an object, the result is that yourvar taxand the model’sthis.attributes.taxare the same thing. So, when you saytax.amount = amount, you’re actually directly editing thetaxthat is inside the model’sattributes.When working with mutable attributes (i.e. anything other than numbers, strings, and booleans), you need to make copies before changing them:
Making a copy also prevents Backbone from thinking that your
setcall isn’t actually doing anything. If you don’t clone thetaxas above, you won’t trigger the change event on the model and that’s probably not what you want.A few examples (open your console please):
_.cloneinsetTax._.cloneand a change handler._.cloneand with a change handler.