Question

I know that you can't pass a parameter to the anonymous function on say, a click event:

$(.....).click(function(e,'parameter-that-can\'t-be-passed'){
})

But why? I don't understand how the event object is even passed to the function. How is a limitation imposed on the anonymous function by the event handler? It just seems kind of strange to me.

Update

For those of you who may stumble upon this question also wondering where the object comes from, it may be due to a lack of knowledge about function callbacks and I encourage you to see this question:

Getting a better understanding of callback functions in JavaScript

Was it helpful?

Solution

JQuery allows a couple of functions that allows you to pass additional data to a click event. Heres an example

HTML :

<button id="button1">HI</button>
<button id="button2">HI</button>

JS :

var custom = "Hello world";

$('#button1').on('click', {txt:custom}, function (e) {

    this.innerHTML = e.data.txt; // button 1 text changes to Hello world
});

var customfn = function (txt) {
    // the scope of the txt argument will be
    // available in the returning function 
    return function () {
        this.innerHTML = txt; // button 2 text changes to BYE
    }
}

$('#button2').on('click', {txt:custom}, customfn("BYE"));

You should also take a look at jQuery.proxy. I haven't tested the code out but the basic idea is there

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top