특정 jQuery 플러그인을 호출하는 핸들러가 있습니다. 나는 코드를 리팩토링하고 프라퍼티를 호출 할 래퍼에 속성과 메소드를 전달할 수있는 객체를 만들고 싶다.jquery 이벤트 핸들러에서 오브젝트 메소드를 전달하는 방법은 무엇입니까?
문제 :
는$("li", opts.tgt).live("click", function() { GetContact(this); });
는 사람이 진행하는 방법에 대한 몇 가지 제안 사항이 있습니까 : 나는 어려움 다음 문을 모방 있나요? 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가 제안한 변형을 사용했습니다. "opts.fnTest ("Test "); 이후 익명 fn 내에서 메소드를 임베드해야하는 이유가 궁금합니다." 상자에서 곧바로 작동하므로 말할 수 있습니다.
$("li", opts.tgt).live({ "click": function() { opts.fnGetData(this); } });
감사합니다, 내 조직 게시물의 끝에서 솔루션을 기록했다. – user1660874
제발하지 말아요 - 정말 스택 오버플로의 Q & A 스타일에 맞지 않습니다. 그러나 투표 화살표 아래의 왼쪽에있는 회색 체크 표시를 클릭하면이 대답을 수락 할 수 있습니다. – ThiefMaster