All about Backbone.js
Model
// To create a model class
var TodoItem = Backbone.Model.extend({});
// To create a model instance
var todoItem = new TodoItem(
{description: 'Pick up milk', status: 'incomplete', id: 1}
);
// To get an attribute
todoItem.get('description');
// To set an attribute
todoItem.set({status: 'complete'});
// RESTful style
var TodoItem = Backbone.Model.extend({urlRoot: '/todos'});
// fetch todo with id=1
var todoItem = new TodoItem({id:1})
todoItem.fetch(); // GET /todos/1
// update the todo
todoItem.set({description: 'Pick up cookies.'});
todoItem.save(); // PUT /todos/1 with JSON params
// create new todo
var todoItem = new TodoItem();
todoItem.set({description: 'Fill prescription.'});
todoItem.save(); // POST /todos with JSON params
todoItem.get('id') // 2
// delete a todo
todoItem.destroy(); // DELETE /todos/2
// Get JSON from model
todoItem.toJSON()
Model Event
// To listen for an event on a model
todoItem.on('event-name', function () {
alert('event-name happend!');
});
// Run the event
todoItem.trigger('event-name');
// To listen for changes
var doThing = function () {
...
}
todoItem.on('change', doThing);
// event triggered on change
todoItem.set({description: 'Fill prescription.'});
// set without triggering event
todoItem.set({description: 'Fill prescription.'}, {silent: true});
// remove event listener
todoItem.off('change', doThing);
Built-in model events
change
|
when an attribute is modified
|
change:<attr>
|
when <attr> is modified
|
destroy
|
When a model is destroyed
|
sync
|
Whenever successfully synced
|
error
|
When model save or validation fails
|
all
|
Any triggered event
|
View
// To create a view class
var TodoView = Backbone.View.extend({
render: function () {
var html = '<h3>' + this.model.get('description') + '</h3>';
this.$el.html(html);
}
});
// To create a view instance
var todoView = new TodoView({model: todoItem});
todoView.render();
console.log(todoView.el); // <div><h3>Pick up milk</h3></div>
// define a view class with tag name
var SimpleView = Backbone.View.extend({tagName: 'li'});
var simple = new SimpleView();
console.log(simpleView.el); // <li></li>
// with id and class
var TodoView = Backbone.View.extend({
tagName: 'article',
id: 'todo-view',
className: 'todo'
});
var todoView = new TodoView();
console.log(todoView.el); // <article id="todo-view" class="todo"></article>
// to use a jQuery method like $.html()
todoView.$el.html();
// to user a template
var TodoView = Backbone.View.extend({
...
template: _.template('<h3><%= description %></h3>'),
render: function () {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
}
});
View Event
var TodoView = Backbone.View.extend({
events: {
'click h3': 'alertStatus' // '<event> <selector>': '<method>', the <selector> should be inside the $el, if <selector> is not specified, the <method> could be trigged by the <event> on any element inside $el
},
alertStatus: function (e) {
alert('Hey you clicked the h3!');
}
});