Backbone Models

by Scott Currell

HTML

<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="http://marionettejs.com/downloads/backbone.marionette.min.js"></script>

JavaScript

var Model = Backbone.Model.extend({
	url: '/users',
	defaults : {
		first : 'John',
		last : 'Doe',
		email : '[email protected]'
	},
	validate : function(atts, ops) {
		if(atts.first === 'Steve') {
			// validationError
			return 'Please enter a better first name than ' + atts.first + '.';
		}
	}
});

// New Model instance
var model = new Model();

console.log(model.get('first')); // John
console.log(model.toJSON());     // first: "John", last: "Doe", email: "[email protected]"
console.log(model.attributes);   // first: "John", last: "Doe", email: "[email protected]"

// On change event
model.on('change:first', function() {
	console.log(model.isValid()); // false
	// validationError requires isValid() check first
	console.log(model.validationError); // Please enter a better first name than ...
});

// Set first name to "Steve" in order to get the change event to fire
model.set('first', 'Steve');