jQuery의 이벤트 시스템을 사용하여 외부 코드에서 플러그인을 구동 할 수 있습니다. 내 이벤트 핸들러에서 'this'는 이벤트가 바인딩되는 요소로 설정되므로 플러그인 메소드에 직접 액세스하는 가장 좋은 방법은 무엇입니까?jQuery 플러그인에서 이벤트 핸들러의 범위 관리
;(function($, window, document, undefined){
var pluginName = "book";
// Standard constructor
function Plugin(element, options){
this.element = element;
this.options = $.extend({}, defaults, options);
this.init();
}
// Simple init
Plugin.prototype.init = function(){
this.setBindings();
}
// Tie local methods to event channels
// so that external code can drive the plugin.
Plugin.prototype.setBindings = function(){
var events = {
'book-open' : this.open,
'book-next-page' : this.toNext,
'book-prev-page' : this.toPrev,
'book-cover' : this.toFront,
'book-back' : this.toBack
}
for(event in events){
var fn = events[event];
console.log(event);
this.$element.on(event, fn);
}
};
// Event Handlers
Plugin.prototype.open = function(){
// when called externally 'this' refers
// to the element the plugin was intialized on.
// I want to be able to call the plugin's 'private'
// methods, like someMethod() below.
};
/* .... other event handlers ... */
// 'Private' plugin methods
Plugin.prototype.someMethod = function(){
// do something
}
// Wrap and return technique from @ajpiano & @addyosmani
$.fn[pluginName] = function (options) {
return this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin(this, options));
}
});
}
})(jQuery, window, document);
당신이 연결 한 스레드에 답이있었습니다. $ .proxy를 사용하면 모든 함수에서 임의의 범위를 정의 할 수 있습니다. 그래서 코드는 이것을 읽어야합니다. $ element.on (event, $ .proxy (fn, this)); – Thomas
왜 익명 함수 내부에서 함수를 래핑 할 필요가 있는지 설명 할 수 있습니까? 이것은 나를 위해 작동하지만 왜 자바 스크립트에서 – asumaran
"이"함수를 호출하는 개체를 의미해야 실현할 수 없다. 다른 개체에 함수 포인터를 첨부하면 해당 함수의 "this"는 실행시에 달라집니다. 따라서 호출하고자하는 함수를 래핑함으로써 객체 "self"에 대한 참조를 생성하고 "self"참조에 대한 메소드를 호출 할 수 있습니다. 그렇게하면 내가 부르는 기능에서 "이"가 무엇을 의미 하는지를 제어 할 수 있습니다. – Caleb