Logic1
Logic1

Reputation: 1847

Attempting to use "this" without having to use "that" while passing functions as parameters to jquery delegate event handlers

Lets say I have some javascript where I have successfully attached two event handler to all of the DOM "li" elements in a DOM unordered list:

function userClickFunction() {
    console.log("USER CLICK");
    clickFunction(this);//had to pass "this" as parameter
}
function autoClickFunction() {
    console.log("AUTO CLICK");
    clickFunction(this);//had to pass "this" as parameter
}
function clickFunction(that) {
    var clickedItem = $(that).attr('id');//using "that" I was able to get the attrs from the "li" element
    console.log("CLICKED!");
}
$("#my_list").delegate("li", "click", userClickFunction);
$("#my_list").delegate("li", "autoClick", autoClickFunction);

Then I trigger those event handlers elsewhere in JS.

$("#some_li").trigger('click');//just kidding, the user does this :P
$("#some_li").trigger('autoClick');//fired by comparing some elaborate timers and interesting state variables.

I was just wondering if there was a more elegant solution to not having to use "that" and what "this" in the function clickFunction() actually refers to? Are there other ways to reference the context of the calling function without having to pass it as a parameter? Thank you!

Upvotes: 0

Views: 34

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can pass a custom context using .call() like below while invoking a function and then can use this inside the callback function

function userClickFunction() {
    console.log("USER CLICK");
    clickFunction.call(this); //had to pass "this" as parameter
}

function autoClickFunction() {
    console.log("AUTO CLICK");
    clickFunction.call(this); //had to pass "this" as parameter
}

function clickFunction() {
    var clickedItem = this.id; //now this refers to the `li` element, also to get the `id` just refer to `this.id` no need to call `attr()`
    console.log("CLICKED!");

Upvotes: 2

Related Questions