A Simple Example – Backbone.js Tutorial Part 2 – Creating an App View

Thanks for checking out part 2 of my Backbone.js tutorial.

In my previous entry I set up a model, a collection, and a view related to a “profile” – essentially bios for the people who work with me at Fortified Studio. The collection grabbed some JSON, used that data to create corresponding models, then displayed the data in a view. I’m still not sure I’m doing things in the best backbone.js way, but it’s working and I don’t think I’m doing anything outrageously against the rules.

Ultimately though, my page needs to have several views, each of which grab their data from JSON files. So I’d like to have a master view that render all the sub-views. I can render my profiles view now, then add other views as I build them.

I’ve seen app views created before, but none of them have struck me as the definitive way to do things. I’m sure I’ve tried this before, but I am once again going to look to the todos.js example for some guidance. Their AppView is somewhat lengthy, but I’ll start slowly and see what I can glean from it.

Firstly, I’ll follow the todos.js lead and bind the view to an existing DOM element. In my case I will bind it to the <body> tag. Is there anything wrong with that? Should I be binding it to a tag within the body? I’ll also use the app view’s initialize method to call fetch on the collection of profiles. Here then, is the very simple first iteration of the app view:

var AppView = Backbone.View.extend({
   el: "body",
   initialize: function() {
      profiles.fetch();
   }
});

Simple and it works. Next I’d like to trigger the rendering of subviews within the app view’s render function. Then again, I guess I don’t need to do this because I’ve already bound the rendering of the profiles to the ‘reset’ event triggered by the profiles collection.

How about if I instead insert all profiles-related instantiations into the app view’s initialize method. This doesn’t affect the functionality, but I suppose it cleans things up a bit.

var AppView = Backbone.View.extend({
   el: "body",
   initialize: function() {
      var profiles = new ProfileList(); 
      var profilesView = new ProfileView({
         model: profiles
      });

      // When profiles have been successfully grabbed,
      // display them using profile template
      profiles.bind('reset', function () {
         profilesView.render();
      });

      profiles.fetch();
   }
 });

Now I only instantiate the app view and the rest takes care of itself.

var App = new AppView;

This seems ok for now. Tomorrow I’ll see what happens when I try to add a second, more complicated subview. Here’s the code from today: backbone.blog.2.zip

Here are some handy links to parts 1 and 3 of this tutorial: