21

There is a heavy memory leak in my application but I haven't found out the causes, and here is the background.

  • I am using AngularJS + JQuery(plugins)
  • Many listeners are bound like the following:

    $(element).on("keyup", function() {});

So the question is

Do I need to unbind those listeners in directives by following?

scope.$on("$destroy", function() {
    $(element).off();
}); 

BTW, how do you usually find out the memory leak in a web application? I use chrome's profile (see here Profiling memory performance) but I could not trace to the codes where memory leaks. Do you have any suggestions?

Thanks a lot!

Edward
  • 939
  • 3
  • 10
  • 17
  • I don't think thats needed unless you are binding all the scopes to $rootScope. – Rishabh Singhal Jul 27 '13 at 13:24
  • 1
    You don't have to remove them, they usually are garbage collected. You may do want to remove listeners of the window though, like scroll or message events if the handler interacts with elements of the scope. See http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory – kapex Oct 18 '13 at 15:26

1 Answers1

14

The Angular documentation for scope destroy, implies that you do need remove DOM events.

http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy

Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

gion_13
  • 41,171
  • 10
  • 96
  • 108
Scott Boring
  • 2,601
  • 1
  • 25
  • 31
  • I have just found that the $destroy evnet is actually triggered after the dom is removed in my case :( time to submit another bug i think – Blowsie Nov 25 '13 at 14:48
  • 1
    @Blowsie There are 2 kind of $destroy event. one is $scope.$on('$destroy',cb) which is called before element removal. Another is element.on('$destroy',cb) which is a jQ event and is called after element removal. Be sure to use the correct one – Le Duc Duy Nov 28 '13 at 05:48
  • 1
    `$scope.$on('$destroy',cb) ` triggers after the content has been removed in my case. 1.2.0 – Blowsie Nov 28 '13 at 09:27