Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbonejs replace $el

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

like image 466
pistacchio Avatar asked Aug 09 '26 16:08

pistacchio


1 Answers

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)
like image 124
Avand Amiri Avatar answered Aug 12 '26 06:08

Avand Amiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!