April 19, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Creating a JavaScript-driven Online Notebook with Backbone.js, Page 2

  • May 13, 2011
  • By W.J. Gilmore
  • Send Email »
  • More Articles »

Creating the Notebook

Next we'll define the model that represents the notebook, or a collection of notes. Notice how this model definition differs from the previous in the sense that we are extending Backbone.Collection rather than Backbone.Model:

window.Notes = Backbone.Collection.extend({
  model: Note,
  localStorage: new Store("notes")
});

window.Notebook = new Notes;

The model property determines what sort of object's make up the collection, which in this case is the Note model defined previously. The localStorage option tells Backbone.js to store the collection in a container on the client. This is an incredibly useful feature for this type of application since the application maintainer doesn't have to deal with storing the user's notes in a database. Finally, following the definition we'll instantiate the model.

Creating the Note View

The NoteView structure presented below determines how each note should be rendered. This is in my estimation the trickiest part to understand. It is responsible for inserting each note into a template (presented below), which is embedded into the page and otherwise not visible to the user.

window.NoteView = Backbone.View.extend ({

  initialize: function() {
    _.bindAll(this, 'render');
    this.model.view = this;
  },

  template: _.template($('#item-template').html()),

  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    this.setContent();
    return this;
  },

  setContent: function() {
    var snippet = this.model.get('snippet');
    this.$('.note').text(snippet);
  }

});

The #item-template template DIV looks like this:

<script id="item-template" type="text/template"></script>

Defining the Application View

All that remains is to tie everything together by defining a view for the entire application, presented below. The el property determines where on the page the "application" exists. Next, the initialize method executes every time the application loads. Note in particular how it binds application view methods to methods residing in the Notebook model (some of these are available by way of the extension, meaning you don't explicitly define them). These bind() calls really sum up the beauty of Backbone.js, allowing you to trigger methods residing in other models based on some page-specific action, such as reloading the page.

I'll talk further about this view following the listing:

window.AppView = Backbone.View.extend ({

  el: $("#notebook"),

  initialize: function() {
    _.bindAll(this, 'saveNote', 'updateNotebook', 'addAll');

    Notebook.bind('add', this.updateNotebook);
    Notebook.bind('refresh', this.addAll);
    Notebook.fetch();

  },

  events: {
    "click #submit": "saveNote",
  },

  addAll: function() {
    Notebook.each(this.updateNotebook)
  },

  updateNotebook: function(note) {
    var view = new NoteView({model: note});
    $("#notes").append(view.render().el);
  },

  newNote: function() {
    return {
      snippet: $("#note").val()
    };
  },

  saveNote: function() {

    Notebook.create(this.newNote());
    $("#note").val("");
  }

});

window.App = new AppView;

The events object literal binds events to methods, causing these methods to fire when the associated event occurs. The addAll() method will execute automatically every time the page loads. Therefore we're going to iterate over the notebook, adding each note to the page. The updateNotebook() method will render a note to the browser. Contrast this with the saveNote() method, which triggers the note create() method in the Notebook model.

Where to From Here?

Admittedly, tracing the execution is by far the hardest part of understanding Backbone.js, so I suggest using the above code to recreate the application, and then insert various alert statements to watch how Backbone.js jumps from one model and view to the next. After a few minutes you'll really start to get a feel for the process, and can then begin to appreciate just how powerful this approach really is.

About the Author

Jason Gilmore -- Contributing Editor, PHP -- is the founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board.


Tags: MVC, JavaScript libraries



Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel