Sam Holguin Sam Holguin - 2 months ago 14
jQuery Question

Why add the custom jQuery plugin name to the scope

More of a 'why', 'than it's broken'...

Can someone explain why you'd add the plugin name to the scope and set an alias here:

(function($, plugin) {
$[plugin] = {
timers: {}
};
$.fn[plugin] = function(type, msg, timeout) {
return this.each(function() {
var $this = $('<p class="' + type + '">' + msg + '</p>').prependTo($(this)),
$sameMsgs = $this.siblings().filter(function() {
return !($(this).html() == msg);
});
$this.hide()[$sameMsgs.length ? 'show' : 'slideDown']();
if ($[plugin].timers[msg]) {
clearTimeout($[plugin].timers[msg]);
$sameMsgs.remove();
}
$[plugin].timers[msg] = setTimeout(function() {
$this.slideUp(function() {
$(this).remove()
});
}, timeout || 2500);
});
};
})(jQuery, "quickResponse");


What I'd like to do is write the plugin like so:

(function($) {

$.fn.quickResponse = function(type, msg, timeout)
{
....
};

})(jQuery);

Answer

If you don't do it this way, you have to repeat your plugin name throughout the code, like this:

(function($) {
    $.quickResponse = {
        timers: {}
    };
    $.fn.quickResponse = function(type, msg, timeout) {
        return this.each(function() {
            var $this = $('<p class="' + type + '">' + msg + '</p>').prependTo($(this)),
                $sameMsgs = $this.siblings().filter(function() {
                    return !($(this).html() == msg);
                });
            $this.hide()[$sameMsgs.length ? 'show' : 'slideDown']();
            if ($.quickResponse.timers[msg]) {
                clearTimeout($[plugin].timers[msg]);
                $sameMsgs.remove();
            }
            $.quickResponse.timers[msg] = setTimeout(function() {
                $this.slideUp(function() {
                    $(this).remove()
                });
            }, timeout || 2500);
        });
    };
})(jQuery);

Then if you decide to rename your plugin, you have to do a global replace of all $.quickResponse and $.fn.quickResponse to the new name.

By using the variable, you only have to change it in one place, the argument to the IIFE.