In my backbone function, how can i remove the elements before i append new elements?, my function all works fine. the issue is while i click on the ‘update’ like, it’s updating the elements and still the older version available. how can i remove the older elements, and append new from update call..?
what is the correct way to clear the existing view elements and append new collections?
my function:
$(document).ready(function(){
var school = {};
school.model = Backbone.Model.extend({
defaults:{
name:'no name',
age:'no age'
}
});
school.collect = Backbone.Collection.extend({
model:school.model,
url:'js/school.json'
});
school.view = Backbone.View.extend({
tagName:'div',
className:'member',
template:$('#newTemp').html(),
render:function(){
var temp = _.template(this.template);
this.$el.html(temp(this.model.toJSON()));
return this;
}
});
school.views = Backbone.View.extend({
el:$('#content'),
events:{
'click #newData' : 'newArrival',
},
initialize:function(){
_.bindAll(this);
this.collection = new school.collect;
this.collection.bind('reset', this.render);
this.collection.fetch();
},
newArrival:function(){
school.views.remove(); // i tried this, throw the error
this.initialize();
},
render:function(){
var that = this;
_.each(this.collection.models, function(item){
that.renderItem(item);
})
},
renderItem:function(item){
//how can i remove the older elements and append new alone?
var newItem = new school.view({model:item});
this.$el.append(newItem.render().el); // keep adding but previous element still not removed,
}
});
var newSchool = new school.views;
})
You need to have a reference to you old views to be able to remove them. You will then be able to to call remove on the child views. I highly recommend that you use backbones remove method instead of just removing elements from the DOM with jquery. Using Backbones remove will also unbind events from the object. To update from server, just call collection.fetch() to get new data. This is my solution (jsfiddle at the bottom):
I have created a working: JSFiddle. Note: In the JSFiddle collection I override fetch() to provide fake data (You should remove that part).