简体   繁体   中英

How to detach and then reattach a Backbone.View without unbinding events?

I have a Backbone system consisting of nested sub-views in which I occasionally need to do the following.

  1. Detach a child view from the DOM
  2. Re-render the parent view from scratch (from a template)
  3. Re-attach the child view at the correct place

I do this by calling something like $(parent.el).html(...) and then $(parent.el).append(child.el)

What I have always seen with this technique is that the event handlers on the child are lost. So I have tried a number of things, none of which have worked so far.

  1. Detaching the child.el first with $.detach()
  2. Cloning the child.el node and reattaching the clone
  3. Calling child.delegateEvents() again after reattaching

The only thing that works for me is completely rebuilding the child view from scratch. Does anyone have any ideas? Reattaching the existing node would be much more efficient.

Thanks!

I just had a similar problem. This seemed to work for me:

this.undelegateEvents();
this.$el.hide();
this.$el.detach();

// do whatever here

this.$el.appendTo(containerElement);
this.delegateEvents();
this.$el.slideDown('fast');

I'm still not exactly sure why the event listeners disappear, though I can confirm they are actually gone when I look in the Chrome developer tools window. It's strange, because Roatin Marth has an example ( http://jsfiddle.net/Xcrhb/1 ) where this problem doesn't occur.

I do exactly the same.

// First of all pre-render child view
childView.render();

// Append in one place
parentView.$el.append(childView.el);

// Detach in another place
childView.$el.detach();

// And append it again
parentView.$el.append(childView.el);

What you're trying to do seems to be hack-ish to Backbone. You would be better off using native functionality by setting up event delegation and re-rendering views instead of detaching, cloning, altering and re-attaching. You don't get any performance increase by doing it.

It would be much easier to help if you explained why you need to do it this way and why native Backbone way of doing things does not work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM