Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap affix plugin memory leak

These lines in the bootstrap affix plugin seem to cause a memory leak because the window gets a reference to the affix instance that's never released.

As a workaround I'm using this code to release the references when removing the affixed element from the DOM:

$(window)
    .off('scroll.bs.affix.data-api')
    .off('click.bs.affix.data-api');

Seems kind of hacky- is there a better way of doing this? Didn't see anything in the affix plugin docs.

like image 277
Jeremy Danyow Avatar asked Feb 11 '14 21:02

Jeremy Danyow


2 Answers

By default, bootstrap Affix listens for scroll and click events on $(window) using the .bs, .affix, and .data-api namespaces.

$.off('.affix'); will remove all listeners in the .affix namespace. $(window).off('.affix'); will remove all listeners in the .affix namespace from the window element. If you only have one Affix, and are affixing it to the window, it has the exact same effect as $.off('.affix');

Adding in the other namespaces makes it more specific, but unless you are using the .affix namespace in your own code, the added specificity doesn't change anything. You don't want to remove the other namespaces independently of .affix if you are using any other bootstrap elements.

$('.affix').off('.affix'); will not work because the listeners are not on the Affixed element, but on the target that element is Affixed to, i.e. the window.

pstenstrm is correct that there is no way to detect that an element is removed from the DOM, or injected for that matter. So if the code later re-injects the element, and you want to behave as an Affix again, you'll need to use the bootstrap JS api to call Affix again.

like image 168
Robin like the bird Avatar answered Oct 11 '22 16:10

Robin like the bird


I took @Carrie Kendall's recommendation and opened a bug report... well commented on a related bug report.

https://github.com/twbs/bootstrap/issues/13655

What we need in this case is a "destroy" method for the affix plugin and some documentation on the getbootstrap site so that people using the affix plugin in single page apps can avoid the memory leak pitfall when removing their affixed content.

like image 36
Jeremy Danyow Avatar answered Oct 11 '22 17:10

Jeremy Danyow