Reputation: 1314
It looks like whenever I call view.remove() it not only removes the view from the dom but also the entire body
I'm calling showView after the creation of each view
showView : function(view) {
if (this.currentView) {
this.currentView.remove();
this.currentView.unbind();
if (this.currentView.onClose) {
this.currentView.onClose();
}
}
this.currentView = view;
$('body').html(this.currentView.render().el);
}
Since there is no longer a body element I cannot add another view
Chrome debugger output:
$('html')
<html>
<script id="tinyhippos-injected">…</script>
<head>…</head>
</html>
Once the view.remove() is ran the screen turns white and doesn't repopulate on $('body').html(this.currentView.render().el);
EDIT:
I changed each view from el: $('.body') to el: '.mainContent' and added a in the index.html file.
In the app.showView I add the mainContent div if it has been removed. Better to remove a div than the entire body.
if($('.mainContent').length == 0)
$('body').append('<div class="mainContent"></div>');
SOLUTION:
I needed to override my view remove method. I didn't want to remove the entire el, just the contents: Recreating a removed view in backbone js
Backbone.View.prototype.remove = function() {
this.undelegateEvents();
this.$el.empty();
return this;
};
Upvotes: 0
Views: 721
Reputation: 5060
Since you are adding the view via $('body').html(this.currentView.render().el);
you don't need to set the el property in the view.
When you set the el property in the view, you are telling backbone to find that element and use it as the base element. When doing that, you don't need to add it to the page with $('body').html()
, you can just call view.render()
. But then when you call remove(), it will remove the el you set (in your case 'body' or '.mainContent').
If you don't specify an el, it generates a new element for you. In that case, you do need to add to the page with $('body').html(this.currentView.render().el);
, but then when you call remove()
it will only remove the generated element.
So, if you just remove el: '.mainContent'
from your views, you can avoid having to check for and re-add that element. Also you will not have to override remove.
After removing el: '.mainContent'
from the view, you can simply do this:
$('body').html(view1.render().el);
view1.remove();
$('body').html(view2.render().el);
Upvotes: 2