Created
November 5, 2015 06:35
-
-
Save runspired/b5e50a2a70b6308ee560 to your computer and use it in GitHub Desktop.
ES6 Fat Arrow ( => ) functions can cause memory leaks when used with Event Handlers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo { | |
constructor(element) { | |
this.element = element; | |
this.setupHandlers(); | |
} | |
doFoo() {} | |
setupHandlers() { | |
this.listener = () => { | |
this.doFoo(); | |
} | |
this.element.addEventListener('scroll', this.listener, true); | |
} | |
destroy() { | |
this.teardownHandlers(); | |
this.element = null; | |
} | |
teardownHandlers() { | |
this.element.removeEventListener('scroll', this.listener, true); | |
// without this next line, the `Foo` instance and any other scope present within the instance | |
// will leak, preventing garbage collection. | |
this.listener = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I assumed I was, and spent a huge amount of time digging through the heap and my code making sure things were properly dereferenced. It's still possible, but at this point highly improbable. I will be digging more.
I have not tested without transpilation.