On Github lporras / backboneRails_Presentation
Created by Luis Porras / @lporras16 Node.js developer at Selfie
You should consider it whether You:
//Define a Model Class
var TodoItem = Backbone.Model.extend({
urlRoot: "/todos",
defaults:{
description: 'Empty todo...',
status: 'incomplete'
}
});
//To Create a model instance
var todoItem = new TodoItem({
description: "attend the lesson",
status: "incomplete",
id: 1
});
//To get an attribute
todoItem.get('description');
//To set and attribute
todoItem.set({status: 'complete'});
var todoItem = new TodoItem();
todoItem.set({description: 'Learn Backbone'});
todoItem.save();
//POST /todos 'todos#create'
var todoItem = new TodoItem({id: 1})
todoItem.fetch();
//GET /todos/1 'todos#show'
todoItem.set({description: "I should clean up my room"})
todoItem.save();
//PUT /todos/1 'todos#update'
todoItem.destroy();
//DELETE /todos/1 'todos#destroy'
//Bind model events
todoItem.on('change', doThing);
//Event triggerd on change
todoItem.set({description: 'Pay all beers tonight'});
//set without triggering event
todoItem.set({description: 'I changed my mind, no beers tonight', {silent: true}});
var TodoList = Backbone.Collection.extend({
model: TodoItem
});
var todoList = new TodoList();
//If you define a comparator, it will be used to mantain the collection in sorted order
var Chapter = Backbone.Model.extend({});
var Chapters = Backbone.Collection.extend({
model: Chapter,
comparator: function(chapter){
return chapter.get("page");
}
});
var chapters = new Chapters([]);
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
console.log(chapters.pluck('title'));
//=> "The Beginning, The Middle, The End"
var TodoView = Backbone.View.extend({
tagName : 'article', //create tag article
id : 'todo-view', //with id 'todo-item
className : 'todo', //and class todo
//template to use
template: _.template( $('#item-template').html() ),
//Listening to DOM events on the view
events: {
'change input': 'toggleStatus'
},
//Every Backbone Class has a constructor method
initialize: function(options){
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
//override this method if the view generates a new DOM Object
render: function(){
return this.$el.html(this.template(this.model.toJSON()));
return this;
},
toggleStatus: function(){
this.model.toggleStatus();
},
//this method delete the view from the DOM
remove: function(){
...
}
});
If you are using JQuery: