Skip to content

Instantly share code, notes, and snippets.

@sagar-ganatra
Created October 5, 2012 14:36
Show Gist options
  • Save sagar-ganatra/3840135 to your computer and use it in GitHub Desktop.
Save sagar-ganatra/3840135 to your computer and use it in GitHub Desktop.
A Backbone Model with constructor
//Create a Car Model
var Car = Backbone.Model.extend({
//Validate the Car Model
validate: function(attr) {
if( !(attr.brand && attr.model && attr.color) ) {
return "Error Occurred";
}
},
//Initialize is called after the Model object is constructed
initialize: function() {
//if there's an validation error invoke this function
this.bind("error", function (model, error) {
console.log(error);
});
console.log('Inside initialize');
},
//Override the constructor
constructor: function (attributes, options) {
console.log('Inside constructor')
//validate the attributes
var validationMsg= this.validate(attributes);
//if validate method returns an error message
if(validationMsg)
return {};
else
//call the Backbone.Model constructor
Backbone.Model.prototype.constructor.call(this, attributes);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment