1

I'm trying to put a $(..).click(function () {... inside a javascript object, but I feel like I'm asking for the impossible.

Inside this object there can be several Dom elements, so I think that making a jQuery extension is excluded too? But I admit, I can not understand how to make an jQuery extension, there are still concepts that escape me in this respect.

Anyway, here's an example of what I'm looking to do, even if it's not functional:

$(document).ready(function() {
  class bt_Fab {
    constructor($elem_ID, $messageBox_ID, message) {
      this.$_ID = $elem_ID;
      this.$_ID_MsgBox = $messageBox_ID;
      this._msg = message;

      this.$_ID.click(function() {
        this.$_ID_MsgBox.text(this._msg); // does nothing...
      });
    }
  };

  var
    myOneButton = new bt_Fab($('#btn_one'), $('#messageBox'), 'message from button one!'),
    myTwoButton = new bt_Fab($('#btn_two'), $('#messageBox'), 'message from button two!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn_one'>button One</button>
<button id='btn_two'>button Two</button>
<!-- lot of html here -->
<div id="messageBox">... </div>

[ Update Edit ] ( for @Sam Hanley & @meagar ) This question is different from How to access the correct `this` inside a callback? because this question is about the use of jQuery function inside a Javascript Object; and they are not about the corect usage of a this in Javascript object model.

1 Answers1

1

In jQuery, within a event handler such as $.click(), the this keyword is overriden with the reference to the sender object, in this case $_ID. In this.$_ID.click, this is actually the instance of the class. Inside of the click handler, i.e. function() { this.msgBox... }, this refers to the element that was clicked.

When I create a class in javascript, I usually create a class variable called my that I set to this in the constructor of the class. Instead of using this use the my variable when you're using jQuery to avoid confusion.

Sometimes it's actually nice that this is overridden, but when you're defining a class it's just horrible.

Glubus
  • 2,819
  • 1
  • 12
  • 26
  • This was just for example. I use myself a 'my=this;' in my Javascript objects. –  Nov 15 '17 at 17:26
  • How would you call the variable "my" without calling "this" ? – Basel Akasha Jul 21 '20 at 20:40
  • I dont really know tbh now that I look at this again. I think what I meant here is that I would create a variable called `my` if I can create it outside of the scope of the jQuery event handling. Meaning the `my` variable already exists within the scope. I dont know if I meant this in the context of a class member when I typed this, and I dont really know at this time. – Glubus Jul 22 '20 at 12:22
  • Got it, Thank you. – Basel Akasha Jul 23 '20 at 18:21