back bone

Backbone.js

 

To declare User model :

 

App.Backbone.User = Backbone.Model.extend();

In above line i am assigning the Backbone model to App.Backbone.User variable .

To declare User Collection :

 

  • we assign the model.

 

  • we bind the add and remove event to collection
App.Backbone.Users = Backbone.Collection.extend({
model : App.Backbone.User,
initialize: function(models, args) {
this.bind(‘add’, this.renderone);
this.bind(‘remove’, this.destroy); },
renderone:function(user){
var view = new App.Backbone.UserView({model: user});
view.render();
var view = new App.Backbone.UserCardView({model: user});
view.render();
},
destroy:function(user){
$(user.view.el).remove();
}
});
  • add event is bind with renderone function
  • remove event with destroy funciton.
  • we can render more than one view while adding .

initialise the Collection  of user

App.Users = new App.Backbone.Users();

add user in collection.

 

var data ={id:’rahul’, username:rahul,firstname:’Rahul’};
App.Users.add(data);

at this point automatically view will be rendered as we bind the add event in collection above.

remove a model

 

App.Users.remove(App.Users.get(‘rahul’));

so on remove view will also remove

User View

 

App.Backbone.UserView = Backbone.View.extend({
tagName: ‘li’,
className: ‘pp-entry group’,
template :_.template(‘<h6><%=username%></h6>’), // very simple can be complex
initialize: function() {
_.bindAll(this, ‘render’);
this.model.bind(‘change’, this.render); // on any change in model the view will render again
this.model.view = this;
},
events:{
“click .addtowallet”:”addlinktowallet”,
},
// Re-render the contents of the Card item.
render: function() {
$(this.el).append(this.templatedetails(this.model.toJSON()));

}
});

 

  • model is binded with the change event , so on every change in model will render the view again automatically.

update a model

var data ={id:’rahul’, username:rahul,firstname:’Rahul’,lastname:’mehta’};
App.Users.get(‘rahul’).set(data);
  • the view also render due to change event in view.

 

References

http://recipeswithbackbone.com/toc.html
http://documentcloud.github.com/backbone/

Advertisements

About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in UI Js. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s