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:
Seems kind of hacky- is there a better way of doing this? Didn’t see anything in the affix plugin docs.
By default, bootstrap Affix listens for
click events on
$(window) using the
$.off('.affix'); will remove all listeners in the
$(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
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.
I took @Carrie Kendall’s recommendation and opened a bug report… well commented on a related bug report.
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.
There is no way to detect when an element is removed from the DOM. The affix plugin can’t automatically remove the listeners. The way you do it is the right way.
Though by calling
$(window).off() you remove every listener, even those you might want to keep. It would be safer to only call
$.off() on the element you are removing.
.data-api after the event name are namespaces. By calling
$.off('.affix') you remove every event declared in that namespace. Which is probably the only better of doing what you’re doing.
- Database Administration Tutorials
- Programming Tutorials & IT News
- Linux & DevOps World
- Ebook Reviews
- PES Matches, Skills & News