1

I'm trying to realize a simple directive in AngularJS. In particular I want to develop a loader button that change its aspect when pressed, and I want to reuse it in all the page of my application that need it.

I have read on the developer guide that:

"There are a few special events that AngularJS emits. When a DOM node that has been compiled with Angular's compiler is destroyed, it emits a $destroy event. Similarly, when an AngularJS scope is destroyed, it broadcasts a $destroy event to listening scopes. By listening to this event, you can remove event listeners that might cause memory leaks. Listeners registered to scopes and elements are automatically cleaned up when they are destroyed, but if you registered a listener on a service, or registered a listener on a DOM node that isn't being deleted, you'll have to clean it up yourself or you risk introducing a memory leak."

In my link function I have put this code for the event listener:

var onLoaderButtonClickEvent = element.on('click', function(){
//Some stuff

});

Now, have I to consider that as a listener on a DOM element (and so I have to remove it) or not? I'm a lit bit confused.

I think that I have not to remove the listener because is on the "element". Is it correct?

Thx to all

thomaux
  • 19,133
  • 10
  • 76
  • 103
ira
  • 866
  • 9
  • 10
  • Why do you think you would have to remove the listener? – Explosion Pills Jan 09 '14 at 04:58
  • Cause I don't understand the difference between "element" and DOM node mentioned in the documentation that I wrote previously. I think that an event like: element.on('click', someFunction) has not to be removed, while an event like: $('#somenode').on('click', somefunction) has to be removed. Is it correct? – ira Jan 09 '14 at 17:38

2 Answers2

3

The element.remove() is called automatically when a directive is destroyed, thus removing all listeners on the element. You only have to remove DOM listeners manually if you attached them to any other DOM elements.

From angular's documentation:

Listeners registered to scopes and elements are automatically cleaned up when they are destroyed, but if you registered a listener on a service, or registered a listener on a DOM node that isn't being deleted, you'll have to clean it up yourself or you risk introducing a memory leak.

timetowonder
  • 5,121
  • 5
  • 34
  • 48
1

The answer is yes. As you've attached an event handler outside of AngularJS, you'll need to clean it up yourself.

You can do this by listening to the $destroy event:

scope.$on('$destroy', function(){
    element.off('click');
});
thomaux
  • 19,133
  • 10
  • 76
  • 103