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