Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access $this in jquery plugin event

I am writing a jQuery plugin and it involves binding an event to window.scroll. The action taken within window.scroll depends on the settings passed in when the original intialization is called.

How do I access the data element, or this, inside a bound 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);
like image 332
BradLaney Avatar asked Oct 10 '22 03:10

BradLaney


1 Answers

jQuery provides a convenience function, $.proxy, that does cross-browser function binding.

(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

like image 86
zetlen Avatar answered Oct 20 '22 03:10

zetlen