I have a View that I instantiate like this:
var myView = new BackboneView({ el: '#some-div'});
In the view render function (that I call from the constructor) I want to replace the current element (I want to wrap it into another div, or place another element before it and make the new element the master element for the view). How to do this? I'm trying this:
this.original_el = this.$el;
this.$el.replaceWith('<div class="new-div"></div>');
Debugging step by step I see the div being replaced on the browser, but this.$el is a still the old value.
On the other hand,
this.$el.setElement('<div class="new-div"></div>');
replaces this.$el, but the new div is not shown on the browser. Any help? Thanks
I have a View that I instantiate like this:
var myView = new BackboneView({ el: '#some-div'});
In the view render function (that I call from the constructor) I want to replace the current element (I want to wrap it into another div, or place another element before it and make the new element the master element for the view). How to do this? I'm trying this:
this.original_el = this.$el;
this.$el.replaceWith('<div class="new-div"></div>');
Debugging step by step I see the div being replaced on the browser, but this.$el is a still the old value.
On the other hand,
this.$el.setElement('<div class="new-div"></div>');
replaces this.$el, but the new div is not shown on the browser. Any help? Thanks
Share Improve this question asked Oct 17, 2012 at 14:20 pistacchiopistacchio 59k110 gold badges287 silver badges434 bronze badges 2- 4 Both :) stackoverflow./questions/11594961/… – nikoshr Commented Oct 17, 2012 at 14:28
- wow, i was so close! ah ah thanks – pistacchio Commented Oct 17, 2012 at 14:31
1 Answer
Reset to default 9I found an issue on the Backbone repo on GitHub. There's good reason that Backbone doesn't do this for you automatically that you can read about there. The solution isto do both, replace $el
in the DOM AND update the Backbone view. In your view method:
this.$el.replaceWith(newElement)
this.setElement(newElement)