BradLaney
BradLaney

Reputation: 2413

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

Upvotes: 5

Views: 571

Answers (2)

zetlen
zetlen

Reputation: 3619

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

Upvotes: 4

Emroot
Emroot

Reputation: 58

You need to define your 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);

Upvotes: 0

Related Questions