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

2
  • Why do you think you would have to remove the listener? Commented Jan 9, 2014 at 4: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? Commented Jan 9, 2014 at 17:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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');
});

2 Comments

this stackoverflow answer says the opposite.
see most voted answer and angular documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.