ivaynberg/select2 — pull request #2566 by akkumanova (2014-07-28 13:49:36+00:00)
Title: Fix memory leak when the dropdown is opened

#### Description
This pull request fixes a memory leak in select2 which is caused by the event handler ([link to code](https://github.com/ivaynberg/select2/blob/7c1acdbe5e4fbcd5920f7a6e06acd46a0c686abf/select2.js#L1399)) on the dropdown mask, which once created is never destroyed.
After opening the select2, the above event handler is registered. The problem is that it references the parent context of the opening function, so that context is never released. And the `that` variable (which holds the `this`) is promoted to the context because it is referenced in [this closure](https://github.com/ivaynberg/select2/blob/7c1acdbe5e4fbcd5920f7a6e06acd46a0c686abf/select2.js#L1437). This kind of memory leak is described in more detail [here](http://point.davidglasser.net/2013/06/27/surprising-javascript-memory-leak.html) and [here](http://mrale.ph/blog/2012/09/23/grokking-v8-closures-for-fun.html).

I've reproduced the leak in [this plunker](http://plnkr.co/edit/tMzQuYKrU4vttztl0Y6p) ([direct link](http://run.plnkr.co/plunks/tMzQuYKrU4vttztl0Y6p)), where after opening the select2 and destroying it there is still a reference to BigObject, which is held by the event handler:
![](http://gyazo.com/06122a0dd00bdc4b0fc9b6d1f2ac4367.png)
The heap snapshot was taken using Chrome 36 in incognito mode.

#### Solution
The memory leak is fixed by creating the event handler in a separate function. [This plunker](http://plnkr.co/edit/Aw3Px5CyCRPTEv0tTJXh) ([direct link](http://run.plnkr.co/plunks/Aw3Px5CyCRPTEv0tTJXh)) is using the fixed version of the code, so you can see that everything is OK.