繁体   English   中英

如何编写一个接受回调函数的jQuery插件方法?

[英]How do I write a jQuery plugin method that accepts a callback function?

我已经在Stack Overflow上阅读了几个类似的案例,但还没有完全像我的一样。 这是我的jQuery插件的要点:

(function($) {
    var methods = {
        init: function() {
            ...
            $(this).myPlugin("close");
            $(this).myPlugin("open");
        },
        open: function() {
            ...
        },
        close: function() {
            ...
        }
    }
})(jQuery);

open()和close()方法涉及jQuery的slideUp()和slideDown()方法,因此我需要能够调用close()方法,然后将open()方法作为回调调用。 但是,当我尝试这个解决方案时,我没有运气。

(function($) {
var methods = {
    init: function() {
        ...
        $(this).myPlugin("close",function() {
            $(this).myPlugin("open");
        }
    },
    open: function() {
        ...
    },
    close: function(options, callback) {

        callback.call($(window));
        ...
    }
}
})(jQuery);

您可以使用此代码..这是调用作为参数传递的函数(回调)的方法。

为了记录,这不起作用:

(function ($) {
    "use strict";

    var methods = {
        init: function () {
            return this.each(function () {
                $(this).click(function () {
                    $(this).myPlugin("close", function () {
                        $(this).myPlugin("open");
                    });
                });
            });
        },
        open: function () {
            return this.each(function () {
                console.log("open was called");

                $(this).children(":hidden").slideDown("slow");
            });
        },
        close: function (callback) {
            return this.each(function () {
                console.log("close was called");

                $(this).children(":visible").slideUp("slow");

                callback.call($(window));
            });
        }
    };
}(jQuery));

上面的代码清楚地表明,在jQuery的幻灯片动画的情况下,在调用open方法之前,脚本的执行不会等待close方法完成。 这是我最终解决的解决方案,使用jQuery promise方法:

(function ($) {
    "use strict";

    var methods = {
        init: function () {
            return this.each(function () {
                $(this).click(function () {
                    $(this).myPlugin("toggle");
                });
            });
        },
        toggle: function () {
            return this.each(function () {
                var $openBox = $(this).children(":visible"),
                    $closedBox = $(this).children(":hidden");

                $openBox.slideUp("fast").promise().done(function () {
                    $closedBox.slideDown("fast");
                });
            });
        }
    };
}(jQuery));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM