2011-08-31 11 views
5

Sto scrivendo un plug-in jQuery e implica il binding di un evento a window.scroll. L'azione eseguita all'interno di window.scroll dipende dalle impostazioni inoltrate quando viene chiamata l'intializzazione originale.

Come accedere all'elemento dati o questo all'interno di un evento associato?

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

risposta

4

jQuery fornisce una funzione di convenienza, $.proxy, che fa vincolante funzione cross-browser.

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

La funzione $ .proxy restituisce una funzione che sarà sempre eseguire la funzione passata nel primo argomento nel contesto del secondo argomento. http://api.jquery.com/jQuery.proxy

+0

Amo questa risposta! – xiaohan2012

0

È necessario definire il campo di applicazione:

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