2011-08-31 84 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);