2

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

pistacchio
  • 56,889
  • 107
  • 278
  • 420

1 Answers1

9

I 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)
Avand Amiri
  • 767
  • 7
  • 13