Why SPA?
var Task = Backbone.Model.extend({
defaults:{ // defaults properties set the default value to the attributes while model instance is created
name:''
},
validate:function(attr){ //validate is place holder method implement in backbone model which need to be overridden
if(attr.name.trim().length < 0){ // validate method is called while model is tried to have it
return "task need to have valid name";
}
}
});
// example
var task_model = new Task();
//set attributes values
task_model.set("name","pick up the cat food"); // set method should be used while change the value of attributes
console.log(task_model.get("name")); // use get method to access the attribute value
console.log(task_model.attributes); // prints out the attribute object
var TaskCollection = Backbone.Collection.extend({
model : Task,
url: '/tasks'
});
var task_collection = new TaskCollection();
task_collection.add(new Task({name:"pay bills"}));
task_collection.create(new Task({name:"pay bills"}); // add
console.log(task_collection.models); // attributes holds the list of task model
console.log(task_collection.toJSON()); // convert all the models in collection into json
console.log(task_collection.at(1)); // gets the model at index 1
var list_view = Backbone.View.extend({
tagName:'li', // tag to be generated while the view is rendered
template:_.template("<span><%= name %></span><span class='remove'>Remove</span>"),
events:{
'click .remove':'remove_task' // binding remove span with click to remove the view on click
},
render:funcntion(){ // a placeholder which has to be overridden by develop to render the content
this.$el.html(template(this.model.toJSON());
return this;
},
remove_task:function(e){
this.remove(); // removing the view self from display or html dom tree
},
});
var form_view = Backbone.View.extend({
el:'#todoform',
events:{
'click button#add':'add_task'
},
add_task:function(e){
this.collection.add((new Task()).set("name",this.$el.find('input#taskname').val()));
}
});
var list_item = new list_view(); // creating a instance of list view
console.log(list_item.render().el);
var form_view = new form_view();
console.log(list_item.el);
// using the underscore extend method to mix regular object to backbone event object
var Event_Aggregator = _.extend({},Backbone.Events);
// example implementation
(function(){
Event_Aggregator.on("random_name",function(mesg){
alert(mesg);
});
})();
Event_Aggregator.trigger("random_name","say hello to the group");
// using this in backbone in demo
var Router = Backbone.Router.extend({
routes:{
"":"home",
"about","about"
},
home:function(){
// my code to display on home page
},
about:function(){
// my code to display about page
}
});
var my_application_routes = new Router(); // create instance of route
console.log(my_application_routes);
Sponsorers