2012-10-12 3 views
1

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); 

답변

2

함수 자체를 전달하는 대신 실행할 함수를 호출 할 수 있습니다.이 함수는 플러그인 주변의 닫는 부분입니다.

this.$element.on(event, fn); 

대신 이제, 함수가 $ 요소를 호출 할 때

this.$element.on(event, this.createBookOpenFunction()); 

전화를 호출하는 대신 다음

var createBookOpenFunction = function() { 
    var self = this; //since you execute this function on the plugin, "this" will be the plugin 
    return function() { 
     self.open(); 
    } 
}; 

, ..., 실제 실행이 이루어집니다 플러그인 객체에서 "self"가 닫혀 있기 때문입니다.
그리고 반환 된 함수를 통해 매개 변수 (있는 경우)를 "self.open()"호출에 공급할 수 있습니다.

또한,이 스레드가 도움이 될 수 있습니다 Controlling the value of 'this' in a jQuery event

는 (내가 직접 jQuery를 사용하지 않는, 그래서 모두가 API에서 사용할 수 있습니다 무엇에 익숙하지 않은,하지만 여기에 일부 게시물이 다른 것 같다 귀하의 문제에 대한 해결책)

+1

당신이 연결 한 스레드에 답이있었습니다. $ .proxy를 사용하면 모든 함수에서 임의의 범위를 정의 할 수 있습니다. 그래서 코드는 이것을 읽어야합니다. $ element.on (event, $ .proxy (fn, this)); – Thomas

+0

왜 익명 함수 내부에서 함수를 래핑 할 필요가 있는지 설명 할 수 있습니까? 이것은 나를 위해 작동하지만 왜 자바 스크립트에서 – asumaran

+2

"이"함수를 호출하는 개체를 의미해야 실현할 수 없다. 다른 개체에 함수 포인터를 첨부하면 해당 함수의 "this"는 실행시에 달라집니다. 따라서 호출하고자하는 함수를 래핑함으로써 객체 "self"에 대한 참조를 생성하고 "self"참조에 대한 메소드를 호출 할 수 있습니다. 그렇게하면 내가 부르는 기능에서 "이"가 무엇을 의미 하는지를 제어 할 수 있습니다. – Caleb

관련 문제