PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 7, 2022

[FIXED] How to reconcile 'this' referencing DOM element and 'this' referencing class?

 July 07, 2022     class, javascript, jquery, this     No comments   

Issue

I'm having an issue understanding how I might go about using the this keyword to refer to a DOM element that is has been clicked, but also using that inside a class where this usually refers to the instance of that class.

Here's a snippet of the relevant code:

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }
  
  selectButton() {
    $(this).toggleClass('selected');
    this.columnController();
  }
  
  columnController(){
    // A function that does something else
  }
}

The issue I'm having is that it doesn't recognize columnController() as a function. I imagine this is because of the scope and how it works with 'this', but I'm not sure how to proceed.

In the above code, selectButton() is successfully applied to all the buttons specified, but the error is given on this.columnController(). Exact console error is:

Uncaught TypeError: this.columnController is not a function

Thank you in advance.


Solution

You can't use this to represent both objects, so pick one and get the other one through some other mechanism.

For example: Use an arrow function to bind the this value to the class, then get the element from the event object.

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }

  selectButton = (event) => {
    $(event.currentTarget).toggleClass('selected');
    this.columnController();
  }

  columnController() {
    console.log("this runs");
  }
}

new Passwords();
.selected {
  background: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="password-column">
  <button class="steel-button">click</button>
</div>



Answered By - Quentin
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing