user1660874
user1660874

Reputation: 41

How to pass object methods in a jquery event handler?

I have a bunch of handlers that call up a specific jQuery plugin. I would like to refactor the code and create an object whose properties and methods can be passed to a wrapper which would then call up the plugin.

Problem: I have difficulties emulating the following statement:

    $("li", opts.tgt).live("click", function () { GetContact(this); });  

Does someone have some suggestions on how to proceed? TIA.

function InitAutoCompleteTest() { // Init custom autocomplete search
    var opts = {
        tgt: "#lstSug", crit: "#selCrit", prfxID: "sg_", urlSrv: gSvcUrl + "SrchForContact",
        fnTest: function (str) { alert(str) }, 
        fnGetData: function (el) { GetContact(el) } 
    }

    $("input", "#divSrchContact").bind({
        "keypress": function (e) { // Block CR (keypress fires before keyup.)
            if (e.keyCode == 13) { e.preventDefault(); }; 
        },
        "keyup": function (e) { // Add suggestion list matching search pattern.               
            opts.el = this; $(this).msautocomplete(opts); e.preventDefault();
        },
        "dblclick": function (e) { // Clear search pattern.
            $(this).val("");
        }
    });

    opts.fnTest("Test"); // Works. Substituting the object method as shown works.


    // Emulation attempts of below statement with object method fail:
    // $("li", opts.tgt).live("click", function () { GetContact(this); });   

    $("li", opts.tgt).live({ "click": opts.fnGetData(this) }); // Hangs.
    $("li", opts.tgt).live({ "click": opts.fnGetData });  // Calls up GetContact(el) but el.id in GetContact(el) is undefined
}

function GetContact(el) {
    // Fired by clicking on #lstSug li. Extract from selected li and call web srv.
    if (!el) { return };

    var contID = el.id, info = $(el).text();
    ...
    return false;
}

Edit

Thanks for the feedback. I finally used the variant proposed by Thiefmaster. I just wonder why the method must be embedded within an anonymous fn, since "opts.fnTest("Test");" works straight out of the box, so to speak.

    $("li", opts.tgt).live({ "click": function () { opts.fnGetData(this); } });

Upvotes: 2

Views: 1985

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318508

Simply wrap them in an anonymous function:

function() {
    opts.fnGetData();
}

Another option that requires a modern JS engine would be using .bind():

opts.fnGetData.bind(opts)

Full examples:

$("li", opts.tgt).live({ "click": opts.fnGetData.bind(opts) });
$("li", opts.tgt).live({ "click": function() { opts.fnGetData(); }});

Inside the callback you then use this to access the object.


If you want to pass the element as an argument, you can do it like this:

$("li", opts.tgt).live({ "click": function() { opts.fnGetData(this); }});

Upvotes: 5

Anton Baksheiev
Anton Baksheiev

Reputation: 2251

From documentation

.live( events, data, handler(eventObject) )

eventsA string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.

data A map of data that will be passed to the event handler.

handler(eventObject) A function to execute at the time the event is triggered.

Example:

$('#id').live('click', {"myValue":"someValue"}, function(evt){
    console.log(evt.data["myValue"]); // someValue
});​

JQuery live

Upvotes: 1

Related Questions