Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 818
maxl0rd Avatar asked Dec 01 '11 15:12

maxl0rd


1 Answers

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.

like image 185
Tom Dalling Avatar answered Sep 26 '22 16:09

Tom Dalling