开发者

jQuery Plugin init binding event to window scroll - how to pass $this?

My first plugin done with a proper architecture, but I'm stuck at how to apply an event listener to $(window).scroll to pin the globalMessage to the top of the window. The full plugin in progress can be seen here: https://开发者_如何学JAVAgist.github.com/937792, but the pertinent bits are the init, below.

What is the best way to set up a window event listener that modifies a css property of the target element?

(function($){

    var methods = {
        init: function(options) {

            var $this = this;
            var opts = $.extend({}, $.fn.globalMessage.defaults, options);
            var data = $this.data('globalMessage');

            // init global data
            if ( ! data ) {
                $this.data('globalMessage', {
                    settings : opts
                });

                $(window).bind("scroll.globalMessage", function() {

                    // ----------
                    // HOW TO ACCESS both $this (defined outside this context)
                    // and the scrollTop value to change top css val?
                    //-----------
                    $this.css("top", $(window).scrollTop());

                });

                $this.bind('click.globalMessage', methods.hide);

            }

            return $this;
        },
        ...[other funcs]...
    }

    ...[main entry point etc]...

})(jQuery);


Passing vars in right way to events:

$(window).bind("scroll.globalMessage", {foo:'bar'}, function(e) {
   alert(e.data.foo); // alert 'bar'
});


If you think about it, there is no this in the context of your methods object. So you need to pass it in through the init() call:

(function($){

    var methods = {
        init: function(sel, options) {

            var $this = $(sel);

And then, when you call your plugin, pass this to your init() method:

$.fn.yourPlugin = function(method) {
    if (!this.length) {
        return this;
    }
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init(this, arguments);
    } else {
        $.error('Method ' +  method + ' does not exist on jQuery.yourPlugin');
    }
};

The only thing I would caution is that at the point the $this variable is set, it's actually a jQuery object, not a specific element. So I have used:

(function($){

    var methods = {
        init: function(sel, options) {

            var $sel = $(sel);

And, as far as using the $this within the event handler, you'll need to redefine it:

$(window).bind("scroll.globalMessage", function() {
    $this = $('#the_selector_for_your_element'); // Maybe $(this)?
    $this.css("top", $(window).scrollTop());
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜