最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbonejs replace $el - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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)
发布评论

评论列表(0)

  1. 暂无评论