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

From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script: include("db_connect.php"); mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $resu ...

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

Using karma for angular to compile directives

I encountered a perplexing issue and now I'm feeling stuck. My main goal is to conduct tests on a list of directives within my project. These Directives have the following structure: angular.module('lessons', []).directive('uwTextare ...

What is the best approach for dynamically accessing or rendering Children within an Angular Component?

I am facing an issue with reusing a component called wrapper with different child components. I found some helpful resources such as this SO question and this article. However, these only address cases where the child component is known in advance. In my s ...

Vue - Passing a parent's ref to a child component as a prop

Is there a way to pass the current component's reference to a child component in Vue.js? <template> <div class="screen" ref="screen"> <child-component :screenRef="screenRef"> </child-component> </div ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

Tips for shortening extra text in a non-wrapping HTML table cell and adding "..." at the end

My HTML template includes text imported from a database field into a <td> tag. The length of the text can range from 3 to 200 characters, and the <td> spans 100% of the screen width. If the text surpasses the width of the screen, I want it to b ...

Laravel is unable to interpret formData

I've been on a quest to find answers, but so far I'm coming up empty. I'm trying to send file input to a Laravel controller via Ajax, but it seems like the controller can't read the data at all. Here is my Ajax code: let fd = n ...

In the node.js application, the route for serving static images from the "/uploads/images" directory using express.static has been found to be dysfunctional

The following Route in my node.js server app API, deployed on the server for fetching images, is not functioning correctly app.use("/uploads/images", express.static(path.join("uploads", "images"))); However, the path below is working perfectly fine app.us ...

The function res.render is not displaying the new page

I have a task that seems straightforward. On my header, I am loading a few a links. <a class="nav-link" href="menu">Menu 1</a> I am attempting to access the URL /menu from this link. In my app.js file: app.use('/', index); app.us ...

Managing timestamps of creation and modification with Sequelize and Postgresql

As a newcomer to Sequelize, I find myself grappling with the intricacies of model timestamps management. Despite prior experience with another ORM in a different language, I'm struggling to wrap my head around how to automatically handle "createdAt" a ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

Can you provide tips on using Ajax to store a cache file?

I've created a javascript/ajax function that retrieves a json file from an external server. The functionality I'm trying to implement includes: Fetching the json file from the external server Saving the json file on the local server Checking if ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

What is the best way to determine the accurate size of a div's content?

There are 2 blocks, and the first one has a click handler that assigns the block's scrollWidth to its width property. There is no padding or borders, but when the property is assigned, one word wraps to the next line. The issue seems to be that scrol ...

How can I switch out an item within FabricJS?

In order to incorporate undo and redo functionality, I have created an array named "history" that stores the most recent changes triggered by canvas.on() events. Displaying console.log: History: (3) […] ​ 0: Object { target: {…} } //initial object ...

Passport Authentication does not initiate a redirect

While working on a local-signup strategy, I encountered an issue where the authentication process against my empty collection was timing out after submitting the form. Despite calling passport.authenticate(), there were no redirects happening and the timeo ...