Reputation: 3196
I am using the jQuery-UI inside of a plugin and am trying to set a callback function for the close:
event of the dialog. I figure I am doing this wrong since it fires immediately (2x) when the page is loaded rather than when the dialog is closed.
Plugin Code
(function($) {
//dynamically add UI CSS
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');
//dynamically add UI JS
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) {
//set default settings
var defaults = {
autoOpen: false,
title: 'Photo Tool',
minHeight: 560,
minWidth: 540,
url: 'http://www.goffinmoleculartechnologies.com/images/no-image-large.png',
onClose: function(){}
};
//extend options to defaults
var opts = $.extend(defaults, options);
return this.each(function() {
$this = $(this);
//create UI dialog
var $dialog = $('<div>')
.html('<img src="' + opts.url + '" width="' + opts.minWidth + '" height="' + minHeight + '" alt="" />')
.dialog({
autoOpen: opts.autoOpen,
title: opts.title,
minHeight: opts.minHeight,
minWidth: opts.minWidth,
modal: true,
close: opts.onClose.call(this) //callback function
});
//add dialog open to click function of caller
$this.click(function() {
$dialog.dialog('open');
return false;
});
});
};
})(jQuery);
Calling Page Code
$(document).ready(function() {
$('.photoLink').photoDialog({
url: 'http://tvrecappersanonymous.files.wordpress.com/2010/03/doozer2.jpg',
title: 'Doozer',
onClose: function() {
alert('Callback'); //fires 2x when page loads
}
});
});
Any suggestions on what I'm doing wrong are appreciated.
Upvotes: 0
Views: 1200
Reputation: 82943
It because you are assigning the result of the opts.onClose callback function execution rather than function. Wrap it in an inline function instead.
Also use a variable to pass this variable to the callback.call.
Change your return statement to:
return this.each(function() {
var $this = $(this);
var that = $(this);
//create UI dialog
var $dialog = $('<div>')
.html('<img src="' + opts.url + '" width="' + opts.minWidth + '" height="' + minHeight + '" alt="" />')
.dialog({
autoOpen: opts.autoOpen,
title: opts.title,
minHeight: opts.minHeight,
minWidth: opts.minWidth,
modal: true,
close: function(){
opts.onClose.call(that) //callback function
}
});
Upvotes: 2