Angular - Implementing selective binding in a function

In my current Angular project, I am utilizing Datatables and buttons to manipulate data. The buttons available are "View", "Mark as completed", and "Mark as incomplete" which trigger specific functions when clicked. To achieve this functionality, the following code is used:

/**
  * Hides ID and adds onclick functionality
  */
  ngAfterViewInit() {
    const table = $('.display').DataTable({
      responsive: true,
      bRetrieve: true
    });
    table.column(0).visible(false);
    this.clickListener(table, this.route);
  }


  /**
  * Listens to row click
  */
  clickListener(table: any, route: any) {
    const self = this;
    let rowData;

    $('.display').on('click', 'tbody tr td .view', function(e) {
      rowData = self.checkIfRowsHidden(table, this, e);
      self.router.navigate([route + '/detail/' + rowData[0]]);
    });

    $('.display').on('click', 'tbody tr td .done', function(e) {
      rowData = self.checkIfRowsHidden(table, this, e);
      self.executePutData(rowData[0], 'Completed', self);
    });

    $('.display').on('click', 'tbody tr td .undone', function(e) {
      rowData = self.checkIfRowsHidden(table, this, e);
      self.executePutData(rowData[0], 'In Progress', self);
    });
  }

The usage of var self = this, serves as a reference to the global scope. Additionally, within the function checkIfRowsHidden, this is used to capture the local scope. This function operates using the local scope in the following manner:

  checkIfRowsHidden(table, scope, event) {
    event.stopImmediatePropagation();
    if (table.responsive.hasHidden()) {
      const parentRow = $(scope).closest("tr").prev()[0];
      return table.row( parentRow ).data();
    } else {
      return table.row($(scope).closest('tr')).data();
    }
  }

In an effort to utilize binding instead of self, I attempted to modify the clickListener function in this way:

  clickListener(table: any, route: any) {
    let rowData;

    $('.display').on('click', 'tbody tr td .view', function(e) {
      rowData = this.checkIfRowsHidden(table, this, e);
      this.router.navigate([route + '/detail/' + rowData[0]]);
    }.bind(this));
    /*rest of the code
    .
    .
    */

However, due to the presence of multiple scopes, the use of this from both the local and global scopes caused errors when fetching data from tables. Is there a method to bind the global scope only to specific items, or is it necessary to resort back to using var self=this?

Answer №1

One useful technique is to implement arrow functions for maintaining global scope. By switching from anonymous functions to arrow functions, you automatically ensure that the global scope is preserved:

$('.display').on('click', 'tbody tr td .view', (e) => {
   rowData = self.checkIfRowsHidden(table, this, e);
   self.router.navigate([route + '/detail/' + rowData[0]]);
});

By taking this approach, there is no need to manually bind the scope since this will accurately reference the Angular component class.

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

Reorganizing Arrays in Javascript: A How-To Guide

I have an array in JavaScript called var rows. [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b0c1e4f9e0ecf1ede4afe2eeec">[email protected]</a>' }, { email: '<a hre ...

Get rid of the strange border on the material dialog

I am struggling with the Angular material 6 dialog component as it is displaying a strange border. I have attempted to remove it using the code below, without success. Interestingly, when I apply the style inline in the browser, it works fine. Any suggesti ...

Hovering over objects in Three.js does not function as effectively as clicking on them

Just getting into Three.js I'm attempting to load a GLTF model and add mouseover and mouseout events. The goal is for the color of the GLTF model to change on mouseover and revert back to the original on mouseout. I have had some success with this, ...

Encountered a runtime error while processing 400 requests

Current Situation: When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. ...

JavaScript constructor functions may trigger ReSharper warnings for naming convention

When it comes to JavaScript coding, I personally prefer using PascalCase for constructor functions and camelCase for other functions. It seems like my ReSharper settings are aligned with this convention. However, when I write code like the following: func ...

What is the best way to add an array containing several objects using Sequelize and Node.js?

I'm facing an issue with inserting an array of multiple objects into the code block below. It doesn't seem to be working as expected. let Bookarray = [{author:"john matt", BookName:"Beauty of Nature"}, {author:"Mick Foley ...

When scrolling, a new page loads seamlessly

Recently, I came across a website that has an interesting feature where new content is loaded automatically while scrolling, seamlessly appending to the existing page. What's more fascinating is that not only does the content change, but the URL also ...

Unlocking the Power of Dependent Types in TypeScript: Unveiling Type by Property Name Declaration

In an attempt to tie the types to the arguments passed, consider the following example: type NS = "num" | "str" type Data<T extends NS> = T extends "num" ? number : string type Func<T extends NS> = (x: Data<T> ...

Upgrading from Angular version 12 to version 14: A Smooth Migration

After upgrading from Angular v12 to v13, I encountered issues while trying to delete the node_modules directory and reinstalling it using npm install. Unfortunately, I received the following errors: D:\test\Fxt\Web\src\main\ui ...

Encountering an Angular 9 unit test issue: "Invalid value utilized in a URL context"

Recently, after upgrading my Angular application from version 8 to version 9, a new error has been popping up while running my Jest unit tests: unsafe value used in a resource URL context (see http://g.co/ng/security#xss) The component undergoing testing ...

You can easily search and select multiple items from a list using checkboxes with Angular and TypeScript's mat elements

I am in need of a specific feature: An input box for text entry along with a multi-select option using checkboxes all in one place. Unfortunately, I have been unable to find any references or resources for implementing these options using the Angular Mat ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

The transition() function in Angular 2.1.0 is malfunctioning

I am struggling to implement animations in my Angular 2 application. I attempted to use an example I found online and did some research, but unfortunately, I have not been successful. Can anyone please assist me? import {Component, trigger, state, anima ...

Analyzing an Object through Functions

var Car = function(name, year) { this.name = name; this.year = year; this.print = function() { console.log(name+" "+year); } } var tesla = new Car("tesla", 2018); tesla.print(); tesla = JSON.parse(JSON.stringify(tesla)); console.l ...

The jquery script tag threw an unexpected ILLEGAL token

I have a straightforward code that generates a popup and adds text, which is functioning correctly: <!DOCTYPE html><html><body><script src='./js/jquery.min.js'></script><script>var blade = window.open("", "BLA ...

The distinction between plural and singular array identifiers in JavaScript

The functionality of this code in Chrome 59.0.3071.115 is causing confusion for me: var names = ["Cat 1", "Cat 2"]; console.log(names); When executed, it displays an array object; however, var name = ["Cat 1", "Cat 2"]; console.log(name); Instead print ...

What method can be used to trigger quirks mode in Chrome by setting the "BackCompat" property on compatMode?

Currently, I am utilizing Selenium for conducting tests on a client's website (an old site over which I have no control and will not be updated by the client). The issue arises when a specific section of the website only functions correctly when runn ...

Transferring variables between PHP pages seamlessly without the need for refreshing the page

I have a situation involving two pages. The first page, named mainform.php, contains a form where users input test results that are then stored in a database upon submission. Within mainform.php, there is a Jira issue slider tab where users can report any ...

Exploring the capabilities of Socket.IO in Node.js for establishing a connection with an external server

Background: My localhost (referred to as Server A) hosts a node.js server, while an external server running node.js can be found at (known as Server B). Although I lack control or access over Server B, which serves as a dashboard site for an IoT device in ...

The parameter always comes up empty when using $state.go in AngularJS

When trying to pass one parameter using `$stete.go`, I encountered an issue. ROUTER $stateProvider.state('login.signin', { url: '/signin', params: { login_event: '' }, templateUrl: "assets/views/login ...