开发者

What purpose does generating a closure inside of the $(document).ready() function accomplish?

开发者 https://www.devze.com 2023-02-27 07:15 出处:网络
Debugging one of my projects I noticed another developer had changed the $(document).ready() function to generate a closure inside of itself. E.G. $(document).ready(function($) { }); I am curious as t

Debugging one of my projects I noticed another developer had changed the $(document).ready() function to generate a closure inside of itself. E.G. $(document).ready(function($) { }); I am curious as to the point of doing this, as well as it's usage.

Note: By removing the $ from the function my code works again. $(document).ready(functi开发者_开发技巧on() { })

Original/Fixed Code

$(document).ready(function() {
    var id = //pull session variable from asp session (yuck)
    var img = $('.photoLink');

    $('.photoLink').click(function() {
        $(this).photoDialog({
            id: id,
            onClose: function() {
                img.attr('src', img.attr('src') + '&rand=' + (new Date()).getTime()); //prevent caching of image
            }
        });
    });
});

Modified/Broken Code

$(document).ready(function($) {
    var id = //pull session variable from asp session (yuck)
    var img = $('.photoLink');

    $('.photoLink').click(function() {
        $(this).photoDialog({
            id: id,
            onClose: function() {
                img.attr('src', img.attr('src') + '&rand=' + (new Date()).getTime()); //prevent caching of image
            }
        });
    });
});

The modified code would produce errors in FireBug stating that the custom plugin function that I was calling did not exist. I am assuming this is because the $ argument is overriding or conflicting with any of the jQuery functions trying to use it.

I'm really confused as to why someone would have changed this, in the current context it makes no sense as that plugin call is the only javascript on the page.

Can someone explain to me why you would use this and possibly an example of it's usage?

Edit

Below is the code for my custom plugin, I also modified the examples above to display how I am calling it:

(function($) {
    var link = $('<link>');
    link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/black-tie/jquery-ui.css'
    }).appendTo('head');

    var script = $('<script>');
    script.attr({
        type: 'text/javascript',
        src: 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js'
    }).appendTo('head');

    $.fn.photoDialog = function(options) {

        var defaults = {
            autoOpen: false,
            title: 'Photo Tool',
            minHeight: 560,
            minWidth: 540,
            url: '/photo_form.aspx',
            onClose: function(){}
        };
        var opts = $.extend(defaults, options);

        return this.each(function() {
            $this = $(this);
            that =$(this);
            var $dialog = $('<div>')
                .html('<iframe src="' + opts.url + '?sn=' + opts.id + '" width="' + (opts.minWidth - 20) + '" height="' + (opts.minHeight - 20) + '" style="border: none;" scrolling="no"></iframe>')
                .dialog({
                    autoOpen: opts.autoOpen,
                    title: opts.title,
                    minHeight: opts.minHeight,
                    minWidth: opts.minWidth,
                    modal: true,
                    close: function() {
                        opts.onClose.call(that);
                    }
                });

            $this.click(function() {
                $dialog.dialog('open');
                return false;
            });
        });
    };
})(jQuery);


When you write a jQuery plugin, to support the noConflict feature, you usually do:

(function($) {
    // Plugin code...
})(jQuery);

That allows you to use $ as an alias for jQuery within the plugin code, regardless of the noConflict settings.

Maybe the other developer added the $ argument by reflex.

On second thought, strike that. The other developer was probably trying to improve the situation.

Your code should still work, even with a $ argument passed to the ready handler. You say the custom plugin function that you were calling does not exist anymore. Can you tell us more about that custom plugin?

I suspect $ is changing between the call to document.ready() and the actual execution of the handler, and you were taking advantage of that before, but you can't anymore since the original $ is now passed to the handler.


the first argument passed to the function inside of $(document).ready(... is the jQuery object. The pattern that you have seen only really makes sense if you had

// outside here, $ could be anything   

jQuery(document).ready(function($) {
    // $ inside here refers to jQuery
    $('.element').click(function() {
        //call custom plugin here
    });
});

This would allow the $ alias to reference jQuery inside of the function to execute when the DOM has loaded, even if window.$ does not reference jQuery but something else, like another JavaScript library function for example. But what you have in your question, so long as window.$ references jQuery, then I would expect the code to be working without problems.


jQuery passes a reference to the global "jQuery" into "ready" handlers. That's why the code would be written that way, and in fact there should be no problem with it. I suspect there's more to this story than your question reveals.

edithere's a possibility: could it be that your plugin is importing a separate copy of jQuery, and that it installs itself on that one instead of yours? You might try using a tool like TamperData or the Chrome "Network" developer tool to watch all the HTTP requests and see if jQuery is being loaded twice. Alternatively, put this line before the "Broken" code:

$.banana = "yellow";

and then check inside your handler code to see whether "$" has a "banana" property or not.

If that's the case, then the difference would be that references in your "Broken" code to "$" would be references to the copy of jQuery that did not have the plugin installed. When you take the "$" parameter out, then the code can refer to the correct, updated copy of the library.

0

精彩评论

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