Memory leak alike condition in script

Consider the following simple markup:

<div.collapsible>
  ...
  <widget.myAspect>...</widget>
</div>

and let’s assume that a) content of this div changes dynamically and widget.myAspect uses the following aspect:

function MyAspect() {
   var container = this.$p(div.collapsible);
   var me = this;
   container.on("collapse", function Foo() { 
      me.doSomething();
   });
}

Note that each time you create <widget.myAspect> the aspect function gets called and  brand new “collapse” event subscription (new instance of function Foo above) gets added to div.collapsible.  Therefore list of subscriptions will grow consuming more and more memory on each DOM change inside the div. Even worse – inner function is a closure that holds me – variable that contains instance of DOM element. So after some time the memory will hold a number of disconnected DOM elements as a pure garbage.

Yes, when the div.collapsible will be removed from the DOM or the window will be destroyed or document reloaded all these dead objects will be freed, but until then your application will demonstrate memory leak alike dynamic.

Thus pay attention on components that subscribe itself to parent’s events. If you do have such situations then consider use of behavior classes instead of aspects and unsubscribe event handlers in detached method. Yet there are other options for that.