4

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(function() { })

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

3 回答 3

4

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.

于 2011-04-19T19:12:47.870 回答
2

传递给函数内部的第一个参数$(document).ready(...是 jQuery 对象。你所看到的模式只有在你拥有的时候才真正有意义

// outside here, $ could be anything   

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

这将允许$别名引用jQuery在 DOM 加载时执行的函数内部,即使window.$不引用jQuery而是其他内容,例如另一个 JavaScript 库函数。但是你的问题是什么,只要window.$references jQuery,那么我希望代码可以正常工作。

于 2011-04-19T19:11:30.320 回答
2

jQuery 将对全局“jQuery”的引用传递给“就绪”处理程序。这就是为什么要这样写代码的原因,实际上它应该没有问题。我怀疑这个故事比你的问题所揭示的更多。

编辑——这是一种可能性:可能是您的插件正在导入一个单独的 jQuery 副本,并且它自己安装在那个副本上而不是您的?您可以尝试使用 TamperData 之类的工具或 Chrome“网络”开发人员工具来查看所有 HTTP 请求并查看 jQuery 是否被加载了两次。或者,将此行放在“Broken”代码之前:

$.banana = "yellow";

然后检查处理程序代码中的“$”是否具有“香蕉”属性。

如果是这种情况,那么不同之处在于“Broken”代码中对“$”的引用将是对未安装插件的 jQuery 副本的引用。当您取出“$”参数时,代码可以引用正确的、更新的库副本。

于 2011-04-19T19:12:16.560 回答