如何在jQuery事件处理程序中传递对象方法? [英] How to pass object methods in a jquery event handler?
问题描述
我有一堆调用特定jQuery插件的处理程序.我想重构代码并创建一个对象,该对象的属性和方法可以传递给包装器,然后包装器将调用该插件.
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); });
有人对如何进行有一些建议吗? TIA.
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;
}
修改
感谢您的反馈.我最终使用了Thiefmaster提出的变体.我只是想知道为什么该方法必须嵌入在匿名fn中,因为"opts.fnTest("Test");可以直接使用,可以这么说.
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); } });
推荐答案
只需将它们包装在匿名函数中即可:
Simply wrap them in an anonymous function:
function() {
opts.fnGetData();
}
另一个需要现代JS引擎的选项将使用.bind()
:
Another option that requires a modern JS engine would be using .bind()
:
opts.fnGetData.bind(opts)
完整示例:
$("li", opts.tgt).live({ "click": opts.fnGetData.bind(opts) });
$("li", opts.tgt).live({ "click": function() { opts.fnGetData(); }});
在回调内部,然后使用this
访问该对象.
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); }});
这篇关于如何在jQuery事件处理程序中传递对象方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!