插件内的jQuery-UI对话框,立即使用回调激活

时间:2011-01-28 23:53:17

标签: jquery-ui jquery-plugins jquery-callback

我正在使用插件中的jQuery-UI,并尝试为对话框的close:事件设置回调函数。我认为我做错了,因为它在加载页面时立即(2x)触发,而不是在对话框关闭时触发。

插件代码

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

致电网页代码

$(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
        }
    });
});

对于我做错的任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:2)

因为你要分配opts.onClose回调函数执行的结果而不是函数。将其包装在内联函数中。

还使用变量将此变量传递给callback.call。

将您的退货声明更改为:

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