Skip to content
This repository has been archived by the owner on Dec 8, 2017. It is now read-only.

Backbone Best Practices

Roger Steve Ruiz edited this page Nov 27, 2015 · 3 revisions

Events and Model Methods (binding/internal-api/etc)

  • No: profile:saveDone or profile:saveSuccess
  • Yes: profile:save:success

Using this more modular 'chaining' pattern we can create methods in the model that are pre-defined such as

var Project = BaseModel.extend({
  initialize: function () {
    this.initializeSaveEventListeners();
  },

  initializeSaveEventListeners: function () {
    var self = this;
    this.listenTo(this, "project:save", function (formData) {
      self.save({
        name: formData['name'],
        description: formData['description']
      },/* success: */function (returnModel) {
        self.trigger("project:save:success", returnModel)
      });
    });
  }
});

This way we can write the models before creating any views or controllers, and can expect them to deliver a "modelName:save" method as well as to deliver on success a "modelName:save:success" method. The success method will return the new model post-persistance, and the "project:save" method will take the form data as an object of key/val pairs that are named the same as they would be in the database and HTML class.

Pre-req:

  • HTML classes named the same as database.

Schema: add_column(:string, :project, :title) should be <input type="text" class="project-title" />.

Then we wrap them up in the view:

data = {
  // DB name / Class name
  title: $(".project-title").val(),
  description: $(".project-description").val()
}

Then we can post the already made model save event with that data:

this.model.trigger("project:save", data) and then this.listenTo(this.model, "change", this.render());

And the render will handle another fetch, and another update of the DOM.

Event Bindings

  • No: this.model.on("profile:save")
  • Yes: this.listenTo(this.model, "profile:save:success", this.test());