What is causing the loss of context for 'this' in the latest Angular 1.5 components?

Encountering a strange issue with the new components. Previously, in version 1.4 directive, we had this block of code...

(function () {
  'use strict';

angular.module('app.board').directive('dcCb', dcClipboardCopy);

  function dcCb() {
    return {
      link : function(scope, elem) {

        var clipboard = new Clipboard(elem[0]);

        elem.on('$destroy', function() {
          clipboard.destroy();
        });
      }
    };
  }
})();

Within the clipboard.destroy() function is the following...

Clipboard.prototype.destroy = function(){
    this.listeners.destroy();
}

In 1.4, this refers to the element like so...

<button class="btn btn-sm btn-menu-outline copy-button" ...

This worked as expected since the button element had the listeners property that could be invoked.

After upgrading to 1.5 and having a component setup like this....

(function() {
  'use strict';
  angular.module('app.board').component('dcCb', {
...
    controller: [ '$element','$scope',function($element,$scope) {

      var self = this;
      self.$postLink = postLink;
      function postLink(){
        var clipboard = new Clipboard($element[0]);
...
        $element.on('$destroy', clipboard.destroy);
      }

    }]
  });
})();

Now, within the destroy function of the Clipboard, this refers to the controller object. Thus, calling this.listeners results in an error.

My First Question : In the newer components, this represents the component scope while it was referring to the button element in version 1.4. Was our approach incorrect back in 1.4?

Second Query : Shouldn't

var clipboard = new Clipboard($element[0])
ensure that the context of this inside the clipboard always points to the clipboard itself (due to the usage of the new keyword)?

Answer №1

When you pass a function defined on a class to event listeners, it is important to consider the execution context. In this case, you are handing off the function from Clipboard to the window and event listeners:

$element.on('$destroy', clipboard.destroy);

To ensure the function executes in the correct context, you can bind it explicitly like this:

$element.on('$destroy', clipboard.destroy.bind(clipboard));

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

The IntroJs step is only partially visible on the screen

Currently, I am incorporating introJS into my application and encountering an issue where one of the steps is only partially visible on the screen. Despite trying various position settings such as auto, left, right, etc., this particular item consistentl ...

Server Receiving Missing Post Parameters

I've developed a straightforward $resource factory. .factory('Order', order) order.$inject = ['$resource', "ApiEndpoint", "UserRecord"]; function order($resource, ApiEndpoint, UserRecord) { return $resource(ApiEndpoint.url + & ...

The hyperlink appears to be malfunctioning with an additional border surrounding it within a pop-up window

I am facing an issue with a link <a> not functioning properly with a popup dialog on . Additionally, there seems to be a border that appears around the <a> when the popup initially displays. If you click on "Leer más" for any product, you can ...

What is the mechanism by which a Node.js server handles incoming requests?

Suppose I am working with this code snippet. I am using ExpressJS, although the server part doesn't seem much different from vanilla Node.js. var express=require('express'); var settings=JSON.parse(fs.readFileSync('settings.json' ...

What are some ways to trigger a controller to update in AngularJS?

I am currently using the Ionic Framework to develop an app and I have encountered a problem. Within my app, there is a Favourites view that displays a list of items that users have favourited elsewhere within the application. The issue at hand is that the ...

Is there a way to utilize flex or other CSS properties to wrap element content onto the next line, beginning from the start of its container?

Is there a way to wrap the text content of an element onto the next line, starting from the beginning of its container? I'm looking for something similar to the image provided. Can this be achieved using flexbox or other CSS properties? Here's a ...

I never rely on the browser back button, I prefer to remain on the same page

Being new to Angular, I have come across the following code snippet: HTML template: <a href="" ng-click="goToCategories();">See categories</a> JS File: $scope.goToCategories= function () { CategoriesService.getCateg ...

How can jQuery determine if multiple selectors are disabled and return true?

I am currently working on a form in which all fields are disabled except for the "textarea" field. The goal is to enable the "valid" button when the user types anything into the textarea while keeping all other inputs disabled. I initially attempted using ...

Using React, a link to the same component is created, but a subcomponent is mistakenly using an outdated version of

Here, we have a SubComponent and a MainComponent created to showcase an image collection. The Subcomponent allows you to toggle between pictures in the collection using the onclick() event. The MainComponent also includes links to other collections, which ...

What steps can I take to position tsParticles behind all other elements in my NextJS project?

In full disclosure, I am not a web developer, so my setup may be incorrect. Currently, the particles are covering all other elements on the page. I would like them to be positioned behind the rest of the elements and only show as a background. import Imag ...

A guide on dynamically sending data to a PHP script when an input is changed and displaying the results in a

I am trying to implement a feature where the data inputted into a text field is sent to posttothis.php and then the result is displayed in a content div. However, I am encountering difficulties in making it work. testscript.html <html> <head> ...

Button click functionality for updating in Classic ASP is functioning correctly exclusively in Internet Explorer and not in other web browsers

Currently, I am in the process of enhancing a Classic ASP application. Within this application, there is an HTML table that is populated from a SQL database. One cell within the table contains checkboxes. Upon clicking one of these checkboxes, a popup wind ...

Can someone assist me in understanding the proper syntax for the Node.js function that inserts a document into Watson's Discovery service from the watson-developer-cloud library?

I'm attempting to upload JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK. Here is the relevant code snippet: const DiscoveryV1 = require('watson-developer-cloud/discovery/v1'); const discovery = new D ...

Ways to address the CORS problem in an ajax function without relying on json

When I run my ajax function: function fn_nextitem(sliderNo){ $.get("/index.php?op=ajax", {slide_no:sliderNo},function(resp) { if (resp) { $('#Div').append(resp); } else { } } This is how my ph ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

The $(document).ready function may not be compatible with Internet Explorer

I have a page with two links - one for registering and one for logging in. Currently, the register link is the most important. When clicked, it loads a .tpl file using jQuery's load function. Within this tpl file, I include a new JavaScript file usin ...

A guide to creating a reference between two tables using the hasOne method in sequelize.js

After generating 3 models using sequelize-auto, let's take a look at them: sequelize.define('users', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

Extracting live content from a website within a native Webview

Running an eCommerce website along with a simple mobile app for both iOS and Android that features a basic tab bar menu, including icons like a shopping cart, profile, refresh button, etc., as well as a Webview to display the website content. The App' ...

What is the best way to relocate a child component to a different parent in React?

I have a list of child components with checkboxes, and when a checkbox is clicked, I want to move that child component inside another div. Below is an illustration of how my app should look. I need to select student names and shift them up under the "Pres ...