-
Notifications
You must be signed in to change notification settings - Fork 4
Backbone Best Practices
- No:
profile:saveDone
orprofile: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.
- No:
this.model.on("profile:save")
- Yes:
this.listenTo(this.model, "profile:save:success", this.test());
Welcome to the Open Opportunities Wiki
- Getting Started