10

I have the following code inside of a directive and I want to make sure it gets cleaned up when the scope is destroyed. I've looked online as well as the code and I was wondering how do I unbind an element.

var window = angular.element($window);
window.bind("resize", function(e){
    abc();
});

Solution:

var abc = function() {};

var window = angular.element($window);
window.bind('resize', abc);

scope.$on('$destroy', function(e) {
    window.unbind('resize', abc);
});
Blake Niemyjski
  • 3,432
  • 3
  • 25
  • 41

1 Answers1

4

Unbind the function from window when the directive's scope gets destroyed. Hence in your directive, you'll invoke a clean up function on the scope's destroy's event:

$scope.$on('$destroy', cleanUp);

Create a cleanUp function and call the jQuery's unbind function.

There is an example in this SO entry, but with the off function instead (which seems similar to unbind, but unavailable in jqLite). Also per this SO entry, you might have to name your function as you'll need to reference it again as a parameter in the unbind call.

Community
  • 1
  • 1
jlr
  • 1,362
  • 10
  • 17
  • 2
    `off` and `on` functions are not available in [`jqLite`](https://docs.angularjs.org/api/ng/function/angular.element). They're in the full jQuery version. `bind` and `unbind` are in `jqLite`. – M.K. Safi Sep 17 '14 at 21:31
  • Ah thanks for the correction, good to know! I've never observed as I use the full jQuery version with Angular. – jlr Sep 17 '14 at 21:34
  • so I just need to call bind and unbind then.. thanks I'll give this an attempt. – Blake Niemyjski Sep 17 '14 at 21:36
  • I think I got it, I just hope the unbind is unbinding the handler :) – Blake Niemyjski Sep 17 '14 at 21:39
  • I updated my question with my solution that I hope is unwiring abc :D – Blake Niemyjski Sep 17 '14 at 21:42
  • Ok that should do it! To check if the unbind is called, you can always profile the application with the Chrome profiler or put a temporary console logging. On the topic of leaks, there is an interesting "3 snapshopts" technique to discover potential leaks [explained here](https://docs.google.com/presentation/d/1wUVmf78gG-ra5aOxvTfYdiLkdGaR9OhXRnOlIcEmu2s/pub?start=false&loop=false&delayms=3000#slide=id.g322f9af_2_22). – jlr Sep 17 '14 at 21:50