Introduction to Backbone.js Part 1: Models - Video Tutorial

If you’ve read my last post or have just been keeping up with the JavaScript world at all, you’ve probably heard about Backbone.js. Well, this is the beginning of a tutorial series for Backbone.js and with this new series also comes a new media type: video! Today’s video tutorial teaches you how to get started using the M from MVC: the model. It’s pretty simple, yet pretty awesome and powerful.

Backbone.js Video Tutorial Series

UPDATE: This tutorial is slightly outdated. I’ve made changes to the code below to match it up with how Backbone works now after version 1.0 was released. Changes:

  • Line 7: 'error' changed to 'invalid'. The name of the event that fires when a model fails to validate has changed from ‘error’ to ‘invalid’ to be more semantic.
  • Line 23: Added , {validate:true}. Models no longer validate automatically when calling set. You must explicitly pass in this option to have it validate.

Final JavaScript Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Person = Backbone.Model.extend({
initialize: function() {
console.log('hello world');
this.bind("change:name", function() {
console.log(this.get('name') + " is now the value for name");
});
this.bind('invalid', function( model, error ) {
console.error(error);
});
},
defaults: {
name: "Bob Hope",
height: "unknown"
},
validate: function ( attributes ) {
if( attributes.name == 'Joe' ) {
return "Uh oh, you're name is Joe!";
}
}
});

var person = new Person();
person.set({name: "Joe", height:"6 feet"}, {validate:true});

console.log(person.toJSON());

Conclusion

This is my first video tutorial so bear with me. I hope you learned something and are eager to learn more. The next video tutorial should come out next Thursday and will be featuring Views. I hope you’re as excited to continue this series as I am. Happy Coding!

Backbone.js Video Tutorial Series

Author: Joe Zimmerman

Author: Joe Zimmerman Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.