Access $ this in jquery plugin event

I am writing a jQuery plugin and associated with binding events to window.scroll. The action performed in window.scroll depends on the parameters passed during initial initialization.

How do I access a data item or to it inside a related event?

 (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);
+5
source share
2 answers

jQuery provides a convenience feature $.proxythat binds between browsers.

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

The $ .proxy function returns a function that will always execute the function passed in the first argument in the context of the second argument. http://api.jquery.com/jQuery.proxy

+4
source

You need to determine the scope:

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

All Articles