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

Backbone.js Models TutorialIf 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

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

About the Author

Author: Joe Zim

Joe Zim

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.


  • Lamo

    Lame

  • Jon

    Great job!  This is a good start to the series.  Keep building onto this.

  • cheferica

    Thanks for this. Looking forward to seeing the next parts.

  • Guest

    No iPad compatible.

    • http://www.joezimjs.com Joe Zimmerman

       What’s not iPad compatible? The video? Try switching to HTML5 video on Youtube.

    • Guest

      Buy an android tablet

  • jperg2tami

    What NotePad++ plugins are you using for code completion / auto completion functionality?

    • http://www.joezimjs.com Joe Zimmerman

       I don’t have a plugin. Just enable it via Setting->Preferences and it’s int he Backup/Auto-Completion tab.

      • jperg2tami

        Thanks for the response… found it!

  • anon

    Nice job

  • http://profiles.google.com/amit.2006.it Amit Gharat

    Good Job, Joe! 

    I would recommend you to explain the backbone built-in methods and properties in detail and the flow of the code execution before you refresh your browser :-)

  • Jimmy 1O9

    Hey, thx for that, really like it, not so much talking, more coding and showing, good :)

  • Alberto

    Great tutorial man, very helpful :)

  • maxw3st

    That flash player is tiny and unreadable. Please use a higher resolution and offer the mid-sized player. This is great stuff, it would be nice to see what you are doing as you go through the tutorial.

    • http://www.joezimjs.com Joe Zimmerman

      If you watch it on Youtube, you can maximize it. I can’t make the player any larger on this template, but I realized my mistake after this video and I upped the font size greatly in my editor in the rest of the videos.

  • harry

    Well.. just like anybody else, i am also trying to start with backbon.js but am not able to pick up with that..

    Is it like we need to be perfect with javascript then only we can start with something like that..

    • http://www.joezimjs.com Joe Zimmerman

       These lessons were aimed at higher level JavaScript programmers. If you’re a complete beginner, then you might want to check out http://www.codecademy.com/ to bring yourself up to speed a bit. It’s an interactive site that walks you through learning JavaScript with quick lessons that you can test out right on their site.

      • hari om Vashishtha

         well.. thanks for that.. now as i am done with the excercises on codeacademy.com what next is advisable..

        • http://www.joezimjs.com Joe Zimmerman

          Books and blogs.
          For blogs, I recommend these: http://www.joezimjs.com/javascript/top-5-resources-for-javascript-knowledge/

          For Books, I recommend the four listed in the footer of this site. I’d start with Getting Good with JavaScript, then jQuery in Action, then JavaScript the Good Parts. You can skip the design patterns book if you want because I pretty much summarized that book on this site in a series of posts and they’re not entirely necessary to know if you’re trying to use a framework like Backbone.

  • Aswani Kumar

    i have done radiostring.com/new in jquery but its becoming defficult to extend, bind events to elements loaded by ajax, code becoming confusing, etc.
    im trying to convert it to backbonejs because of its mvc and event binding. backbonejs is very nice yet confusing. can you please help. have a look at it.

    • http://www.joezimjs.com Joe Zimmerman

       What exactly are you confused about? Did you go through the entire 5 part series of videos?

      • Aswani Kumar

        yeah, its confusing, so, im trying angularjs.

        • http://www.joezimjs.com Joe Zimmerman

          Actually, if you were going to try another MVC, I’d recommend Ember.

  • http://twitter.com/marcelkalveram Marcel Kalveram

    That looks like a great series, I have already tried the backbone.js introduction on peepcode, but I always like to get things explained twice or from different angles to get a better understanding. Thanks!

    • http://www.joezimjs.com Joe Zimmerman

      You’re very welcome.

  • Atif

    Joe. Please release text version of these video tutorials .. because.
    1) As it is 2012 but many of the internet users around the world have poor net connection.

    2) Not everybody can understand spoken English well.

    Thank you,

    Muhammad Atif Ibrahim
    Karachi, Pakistan.

    • http://www.joezimjs.com Joe Zimmerman

      I’m sorry but I don’t have the time to do that. Besides, the main reason I use screencasts is because it’s easier to show things and demonstrate them than it is to show a large block of code and then walk through that code.

      • http://www.martinsmucker.com Michael Martin-Smucker

        I would add 3) Some of us forgot to bring our headphones to work. ;)

        I’ll be sure to check back when I’m home… this looks like a great resource.

  • http://twitter.com/jonniekang jonnie kang

    these are very nice thanks!

  • tim o’connor

    Hi Joe, thanks for the tut. I think there may have been a code change in backbone since as you example looks to be now giving errors. One is generated in the backbone.js file and the other in the html file.

    TypeError: f is undefined backbone-min.js (line 10)
    TypeError: Backbone.Model.extend is not a function test.html (line 22)

    validate: function ( attributes ) {

    thanks,Tim.

    • tim o’connor

      HI Joe, found what was causing the problem, I was importing backbone before underscore.js in the header and that what was causing the error.
      oh well.. Thanks again, great work btw!

      • http://www.joezimjs.com Joe Zimmerman

        I’m glad you found it.

  • Erick The Red

    Pretty cool you got all this tutorials for backbonejs, its just what I was looking for.
    btw do you have a downloadable link to the tutorial files?Thanks

    • http://www.joezimjs.com Joe Zimmerman

      I don’t have a link to any files for these first 5 tutorials, but I do have the Application Walkthrough code up on GitHub: https://github.com/joezimjs/Wine-Cellar

  • http://twitter.com/Seanmyr Sean Meyer

    I’m confused about something. I’m completely new to backbone.js and I went through your first little tutorial on it and I don’t understand something. Actually a couple of things. There is a “validate” method created but nowhere in the code do I see that method actually getting called. What’s more, how does it know when it does call the validate method that it was an error and therefore to go with the bind on error and display that message as an error?

    If you could tell me how these two things happen I would really appreciate it.

    Thanks

    • http://www.joezimjs.com Joe Zimmerman

      Sure thing. Validate is called internally by Backbone every time you set a value or save the model. The “error” event is fired every time that there is a validation error. If the validate function returns a string, then it was an error, otherwise there is no error. I can’t tell you what it’ll do if you return something other than a string, since I haven’t tried it, but if there isn’t an error, then don’t return anything and you should be fine.

  • david

    Hi, it is really a good blog to learn backbone. Thanks for creating it. For starters, I have downloaded the notepad++ but it does not shows auto suggestion (functions) like the one you show in the video. It would be helpful if you could shows what are the plugins to setup the IDE so that it could show the drop down suggestion as we type.

    • http://www.joezimjs.com Joe Zimmerman

      Please read my reply to this question in a comment below. The question was asked by @jperg2tami:disqus

  • http://www.facebook.com/zimmer.joerg Jörg Zimmer

    Hi Joe, thanks for the tutorial. What I don’t get is why that last JSON output states Bob Hope, unkonown and not Joe, 6 feet? Thanks in advance

    • http://www.facebook.com/zimmer.joerg Jörg Zimmer

      Found a possible explanation myself: It’s not set to Joe, 6 feet because the validation failed as you have set ‘Joe’ to a non valid name just by stating a return value in validate. So the object remains on default values. Am I right?

      • http://www.joezimjs.com Joe Zimmerman

        Correct. When a `set` call fails validation, it doesn’t actually set those values. Validation in relation to using `set` is handled very differently now, so make sure to read the docs when 1.0 is released (I’ve talked with the developers and they might not change the docs to reflect these changes until 1.0 is released)

  • Parry

    For Backbone.js version 0.9.10+

    – ‘invalid’ event is triggered instead of ‘error’ during validation
    – one had to implicitly pass ‘{validate:true}’ to the set method

    Suggested Change:

    Line 7
    -this.bind(‘error’, function( model, error ) {
    +this.bind(‘invalid’, function(model, error) {

    Line 23
    -person.set({name: “Joe”, height:”6 feet”});
    +person.set({name: “Joe”, height:”6 feet”},{validate:true});

    For more information visit:
    https://github.com/documentcloud/backbone/issues/2153

    • http://www.joezimjs.com Joe Zimmerman

      You’re absolutely right. At some point when 1.0 comes out, I’ll be going over the differences and showing of the new capabilities.

    • Vinicius da Costa Pires

      Exactly what I was looking for. Thanks :)

  • 郭清

    字太小了哦,看起来好难受!