I'm new to backbone and i'm trying to re-render the contents of a view. I've put up the code in jsfiddle ...
http://jsfiddle.net/rzYLU/11/
So when user clicks re-render how can i remove the contents in the dom and show only the new items ?
I'm new to backbone and i'm trying to re-render the contents of a view. I've put up the code in jsfiddle ...
http://jsfiddle.net/rzYLU/11/
So when user clicks re-render how can i remove the contents in the dom and show only the new items ?
The safest thing to do is to keep track of your QuestionView
instances inside your AppView
. Then you can call remove
on each QuestionView
before adding the new ones; the remove
method is a:
Convenience function for removing the view from the DOM. Equivalent to calling
$(view.el).remove()
;
Views should provide their own remove
implementation to unbind from non-DOM events and thus prevent zombies. The default simply removes the view's el
from the DOM but if you do it right from the beginning, things will keep working nicely when your code inevitably changes.
First adjust your QuestionView
to have a remove
method to remove the event you've bound to the model:
var QuestionView = Backbone.View.extend({
//...
remove: function() {
this.model.off('change', this.render);
this.$el.remove();
}
});
Then you'll need a couple adjustments to AppView
to keep track of your QuestionView
s:
var AppView = Backbone.View.extend({
//...
initialize: function() {
//...
this.sub_views = [ ];
//...
},
//...
addOne: function(question) {
var view = new QuestionView({
model: question
});
this.sub_views.push(view); // <----------------------- Add this
this.$("#question-list").append(view.render().el);
},
addAll: function() {
for(var i = 0; i < this.sub_views.length; ++i) // <--- And these three lines
this.sub_views[i].remove();
this.sub_views = [ ];
Questions.each(this.addOne);
}
Demo: http://jsfiddle.net/ambiguous/FF9eG/
I've also updated your code to use on
and off
instead of bind
and unbind
to match the new style. Newer versions of Backbone also have a cached version of $(this.el)
in this.$el
so I've updated the code to use that as well.