2011-08-31 5 views
5

jQuery 플러그인을 작성 중이며 이벤트를 window.scroll에 바인딩해야합니다. window.scroll 내에서 수행되는 동작은 원래 초기화가 호출 될 때 전달 된 설정에 따라 다릅니다.

바운드 이벤트 내에서 데이터 요소 또는 여기에 어떻게 액세스합니까?

(function($) { 
    var methods = { 
     init : function(options) { 
      return this.each(function() { 
       $(window).bind("scroll.myPlugin", methods.windowOnScroll); 
      }); 
     }, 
     windowOnScroll : function() { 
      var $this = $(this); 
      var data = $this.data("scrollingLoader"); 
      if (data.something) { 
       // ... 
      } 
     } 
    })(jQuery); 

답변

4

jQuery를 크로스 브라우저 기능이 결합 않는 편리한 기능, $.proxy을 제공합니다.

(function($) { 
    var methods = { 
     init : function(options) { 
      return this.each(function() { 
       $(window).bind("scroll.myPlugin", $.proxy(methods.windowOnScroll,methods)); 
      }); 
     }, 
     windowOnScroll : function() { 
      var $this = $(this); 
      var data = $this.data("scrollingLoader"); 
      if (data.something) { 
       // ... 
      } 
     } 
    })(jQuery); 

$ .proxy 함수는 두 번째 인수의 컨텍스트에서 첫 번째 인수에서 전달 된 함수를 항상 실행하는 함수를 반환합니다. http://api.jquery.com/jQuery.proxy

+0

나는이 답변을 좋아합니다! – xiaohan2012

0

당신은 당신의 범위를 정의해야합니다

(function($) { 
    var methods = { 
     init : function(options) { 
      return this.each(function() { 
       var scope = this; 
       $(window).bind("scroll.myPlugin", function(){ 
        methods.windowOnScroll.call(scope); 
       }); 
      }); 
     }, 
     windowOnScroll : function() { 
      var $this = $(this); 
      var data = $this.data("scrollingLoader"); 
      if (data.something) { 
       // ... 
      } 
     } 
    })(jQuery);