Recently, I encountered a challenge while attempting to remove an event in my AngularJS directive from within a function that acts as the event handler for angular.element($window).on()
.
Through this experience, I learned that when unbinding from the current directive only, it is necessary to pass the same event handler to both angular.element().on()
and angular.element().off()
AngularJS - Unbind $window of an event from specific directive.
This particular situation involves a controller method within 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));
}
I would greatly appreciate any assistance in understanding why the attempt to unbind the event is not successful!
Note: Initially, I tried passing just eventHandler
to both the .on()
and .off()
functions. However, I realized that this
was not referring to the eventHandler
function, which led me to call it with .bind(eventHandler)
.