Alireza
Alireza

Reputation: 4516

Using jQuery event handlers inside Javascript class constructor

I'm new to OOP in Javascript, I've been changing some of my older codes to make reusable code.I decided to turn them, instead of some inline codes, into some Javascript classes.

So here's my class:

    function TreeStructure(psi, csi, csc, kwargs) {
        this.parentSelectorId       = psi;
        this.childrenSelectorId     = csi;
        this.childrenSelectorClass  = csc;
    
        kwargs = (typeof kwargs === "undefined") ? 'NoOptionalArguments' : kwargs;
    
        // First Question

        $('#' + this.parentSelectorId).click(this.parentSelectHandler());

        // Second Question 
        $('#' + this.parentSelectorId).on('click', this.parentSelectHandler(e));        
    }; 

    TreeStructure.prototype.parentSelectHandler = function () {
        alert("Why is it called after page loads ?!?
                       it's attached to a click handler   huh?");    
    }

And usage of the class:

    $(document).ready(function(){
         tree = new TreeStructure('blahId', 'blahId', 'blahClass');
    });

But when running this, Unexpected events (for me) happen. So here's my two questions:

  1. Why is parentSelectHandler function called after page loads? (I think the expected behavior is to be called after the selector has been clicked)
  2. In jQuery Event handlers, I can get the event and pass it to the event handler function, but when I try to pass parentSelectHandler, an argument 'e', it says it's not defined.

So can anyone please help me ?

Upvotes: 2

Views: 4233

Answers (2)

jcubic
jcubic

Reputation: 66490

You're not passing a function but you execute it and then pass return value to click, you need to pass a function.

$('#' + this.parentSelectorId).click(this.parentSelectHandler);

and if you pass that method to click handler the context will be change so you need to wrap it with anonymous function that will keep the context:

var self = this;
$('#' + this.parentSelectorId).click(function(e) {
  self.parentSelectHandler(e);
});

or use bind method

$('#' + this.parentSelectorId).click(this.parentSelectHandler.bind(this));

Upvotes: 3

Patrick Evans
Patrick Evans

Reputation: 42736

it is executing because you are executing, and subsequently setting its return value as the callback, it instead of setting it itself as the callback

$('#' + this.parentSelectorId).on('click', this.parentSelectHandler(e)); 

should be

$('#' + this.parentSelectorId).on('click', this.parentSelectHandler);

if you are wanting to capture the event object then modify the anonymous function to

TreeStructure.prototype.parentSelectHandler = function (e) {

this will make e hold the event object

Upvotes: 3

Related Questions