collection and view in back bone
var studentmodel = Backbone.Model.extend();
var studentcollection = Backbone.Collection.extend({
model : studentmodel,
url : 'http://localhost/bb/data.JSON',
parse : function(response){
//console.log(response.data);
return response.data;
//return response;
},
});
var studentlistview = Backbone.View.extend({
tagName : "ul",
className : "studentlistul",
initialize : function(){
this.model.bind("reset", this.checkEvent,this);
this.model.bind("add", this.checkEvent,this);
},
checkEvent : function(){
$(this.el).html("");
_.each(this.model.models, function(student){
$(this.el).append(new studentListItemView({ model : student}).render2().el);
}, this);
$('#studentlistdiv').html($(this.el));
return this;
}
});
and try to add items to this model and its work, my question is that inside render fn how can i get the event type while this.model.bind(“add”, this.checkEvent,this) this evt fire. inside checkEvent how can i get the type of event ie which one fired add or reset. this is my question plz help me
There is no reliable way for a Backbone event handler to know what event triggered it. Instead of doing this:
you should have separate handlers for each desired action:
and then your
renderwould look sort of like this:A couple extra things while I’m here:
this.elinthis.$elso there’s no need to$(this.el), just usethis.$el.collectionoption the same way they handlemodel. So if younew View({ collection: c })then the view will automatically havethis.collection. If you have a collection, usecollectionand if you have a model, usemodel; using accurate names is less confusing.this.collection.each(...)instead of_(this.collection.models, ...).