Is it possible to unbind an event within the same function that was passed to bind in AngularJS

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).

Answer №1

I quickly notice two issues.

1) Using bind() will create a new function with the bound values.

2) The second bind() call within the function serves no purpose.

Referencing information from MDN's website

The bind() method generates a new function (known as a bound function) with the same internal function body as the original function that is being bound, and the value of 'this' is set to the first argument provided to bind(). This value cannot be changed.

Therefore, when using off(), simply provide the event name without the need for a second parameter. The handler will be unique because bind() has been applied to it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you convert an array into a string by including the numerical values of each element within the array?

var array = ['a', 'b', 'c'] function arrayTransform(array) { if (array.lengths === 0) { console.log("Empty") } else { console.log(array.join()); } } arrayTransform(array); The expected result should be 1.a, 2.b ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

"Using Laravel and Ajax, the foreach loop in the Controller is configured to return a singular

When attempting to retrieve names from the database using Ajax and a foreach loop in the controller, only one name is returned instead of both. I have explored solutions where people suggest using foreach in the view, but since I am using Ajax in the view, ...

What is the solution for resolving the error message "handling locally caught exception"?

When dealing with a REST API call, the function responsible for handling it may encounter situations where various functions called to process parts of the request throw errors indicating that an error code should be returned as a response. Additionally, t ...

Stopping the ability to navigate within an Ionic application

I am attempting to block navigation and display a popup in a controller. $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { if(someConditionMet) { event.preventDefault(); showPopup(); } } ...

Issue with useEffect causing a delay in updating the state value

I'm facing an issue with a component that displays the number of people who have liked a book. The problem is, I can't seem to consistently get the correct result in my states. Here's the code snippet: ///Fetching the book details cons ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...

How can you modify the encapsulation of a third-party component in an Angular application?

Utilizing AngularElements with native encapsulation allows bs4 components to be used in a bs3 project. For example: @Component({ selector: 'app-my-button', templateUrl: './my-button.component.html', encapsulation: ViewEncapsulati ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

Instructions for showcasing an image taken using cordova-plugin-media-capture

I recently implemented this specific plugin in my project which allows me to easily capture images using my Android device. However, I'm encountering some difficulties when trying to display the images that are captured within my app. After attemptin ...

What is the best way to combine two arrays of objects into a nested tree format?

I am facing a challenge with 2 arrays of objects. Let's call them Array A and Array B. [ { value: 'Node 1', id: 1, childs: [ { value: 'Node 2', id : 2, ...

Grunt Alert: Unable to locate "concat" task

I'm having some trouble starting with a basic Grunt example, specifically encountering an issue with grunt-contrib-concat. This is my setup in Gruntfile.js: $ cat Gruntfile.js module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.f ...

Using a Firebase token repeatedly: simple steps to follow

I have integrated Firebase Web Notification using Firebase SDK. The implementation process involves two files: a) generate-token.js and b) firebase-messaging.sw.js To get access token, permission is requested by calling requestPermission function. Upon ...

The innerHTML property of the elements obtained using document.getElementsByClassName("") is currently malfunctioning

In my HTML file, I have a div element with the class name today. I am attempting to display the temperature on this element by using the code below. However, it seems that nothing is being printed on the div element. Can you please assist me with this is ...

You cannot link to the innerHTML containing bookmarks from a different page

Using JavaScript AJAX, I am including a file called cards.html into a parent HTML page named index.html. The included cards.html file consists of a list of cards, each containing a bookmark in the form <li id="byx-123_shapes">. However, w ...

Is there a way for me to receive notifications about errors while piping to gulp browserify?

I am leveraging browserify to utilize npm modules in my front end code, and I use gulp for my build tasks. The setup is functioning smoothly: const browserify = require('gulp-browserify'); gulp.task('js', ['clean'], function ...

Issue with AngularJS filter failing to properly filter data

This is the response I received in JSON format from a web service. [{"cid":"41","scname":"Baby Soap","scid":"1"},{"cid":"41","scname":"Baby Powder","scid":"2"},{"cid":"41","scname":"Baby Food","scid":"3"},{"cid":"41","scname":"Diapers","scid":"4"},... // ...

The JSSProvider is not creating a class prefix when using the classNamePrefix option

Currently, I am facing an issue with material-react in my React project. Both the shell and micro-frontend are using material-react, resulting in identical class names such as .jss1 and .jss2. This is causing a clash in styles. I have attempted to generat ...

Unable to load the casperjs module located in the parent node_modules directory along with spookyjs

Currently, I have only spookyjs installed in the node_modules directory of my project. However, I am facing an issue where I can only run my scripts (including the default one) successfully if casperjs is installed globally with the (-g) flag, instead of h ...

Create a custom URL based on the text provided

I have a task of creating a new URL based on user input text Name: <input type="text" id="myText" > <button onclick="myFunction()">check tracking</button> When using DHL service, it requires adding a specific code to the URL like this: ...