Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Sure thing.

But first, for the "kinds of things" that Backbone helps with, take a quick scroll through the list of examples available here: http://backbonejs.org/#examples

Here's a bit of typical (if exaggerated) jQuery to render/update the UI for a list of "accounts":

    $(".account").each(function(){
      var id = $(this).attr('data-id');
      var data = window.accountJSON[id];
      $(this).find(".name").text(data.name);
      for (var i = 0, l = data.emails.length; i < l; i++) {
        var e = data.emails[i];
        $(this).append($("<div class='email'></div>").text(e));
      }
      var addresses = $(this).find(".address").length;
      $(this).find(".address_count").text(addresses);
    });
... note that we're looking into specific DOM classes, pulling data from a big 'ol global JSON object, looking up id values from the DOM, and so on.

Here's something a little bit closer you really want to write instead:

    Accounts.each(function(account) {
      new AccountView({model: account});
    });
For each account, render its UI. Of course, this is just sweeping a lot of the complexity of the original example under the rug -- but that's the point -- you want your UI in HTML templates, and your data/model logic to be in "clean" JavaScript code unpolluted by UI concerns. Then, when you refactor your design later, all of your client-side business logic doesn't have to change -- it no longer cares about global nested JSON structures or concrete DOM elements.

For another Backbone example, imagine taking all of the songs by a given artist, and rating them with 5 stars:

    Songs.each(function(song) {
      if (song.get('artist') == "Wire") {
        song.set({stars: 5});
      }
    });
... and your UI updates accordingly, and you can change that ".set" to a ".save" call to persist the tracks back to your server as well.


Ask and ye shall receive. An answer from the library author. Doesn't get much better than that.


Thanks a lot jashkenas.

I have to admit that whenever I see “MVC something” a lazy instinct kicks in. Probably because it seems like an overkill and I know I can code something in a few minutes (which is never true) that will do the same without having to learn it.

Usually, learning is most fun for me when I have a problem to solve or when I get really curious about something.

And that song example falls in the second category.


I wish your jQuery code was exaggerated...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: