开发者

Access $this in jquery plugin event

I am writing a jQuery plugin and it involves binding an event to win开发者_如何学Godow.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);


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜