0

I'm trying to unbind an event in my AngularJS directive within a function that is passed as the event handler to angular.element($window).on().

From this question, I've come to realise that to unbind from the current directive only, the same event handler must be passed to both angular.element().on() and angular.element().off()

AngularJS - Unbind $window of an event from specific directive.

This is my controller method within a the object returned by the directive;

controller: function($scope, $element) {
            var eventHandler = function() {
                var windowBottom  = $window.pageYOffset + $window.innerHeight;
                var elementBottom = $element[0].getBoundingClientRect().bottom;
                if (windowBottom > elementBottom) {
                    console.log($scope.stockID, this);
                    angular.element($window).off('scroll', this.bind(this));
                }
            };
            angular.element($window).on('scroll', eventHandler.bind(eventHandler));
        }

Any help understanding why this is failing to unbind the event would be much appreciated!

Note: I originally tried passing just eventHandler to both the .on() and .off() functions, however I realised that this wasn't referencing the eventHandler function, hence why I've called it with .bind(eventHandler).

Community
  • 1
  • 1
  • There can be multiple controllers on a page at once. I see a memory leak here, if the events get bound every time one of these controllers are instantiated and there's nothing that guarantees that they will be removed. You might want to remove the event once the scope is destroyed as well. – arjabbar Sep 08 '15 at 20:29

1 Answers1

1

Two things I immediately see wrong.

1) Calling bind() returns a new function with the bound values.

2) The second calling to bind() inside the function, does nothing.

From MDN's site

The bind() function creates a new function (a bound function) with the same function body (internal call property in ECMAScript 5 terms) as the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind(), which cannot be overridden.

So basically, when you call off() you only need to pass in the event name. Get rid of that second parameter. That handler will be different from the one that was passed in initially since you're calling bind() on it.

arjabbar
  • 6,044
  • 4
  • 30
  • 46