用JS/jQuery以编程方式实现回调

vzw*_*ick 10 javascript jquery design-patterns callback

所以,我正在写一个网络应用程序.几乎所有东西都是在客户端完成的,服务器只是一个RESTful接口.我正在使用jQuery作为我的选择框架,并在Revealing Module Pattern中实现我的代码.

我的代码的线框基本上看起来像这样:

(function($){
    $.fn.myplugin = function(method)
    {
        if (mp[method])
        {
            return mp[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || ! method)
        {
            return mp.init.apply(this, arguments);
        }
        else
        {
            $.error('Method ' +  method + ' does not exist on $.myplugin');
        }
    };

    var mp =
    {
        init : function( options )
        {
            return this.each(function()
            {
                // stuff
            }
        },
        callbacks : {},
        addCallback : function(hook_name, cb_func, priority)
        {
            // some sanity checking, then push cb_func onto a stack in mp.callbacks[hook_name]
        },
        doCallbacks : function(hook_name)
        {
            if (!hook_name) { hook_name = arguments.callee.caller.name; }
            // check if any callbacks have been registered for hook_name, if so, execute one after the other
        }
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

很简单,对吧?

现在,我们能够从应用程序范围内部以及外部注册(多个,分层)回调.

什么在困扰我:为了让整个事情尽可能地扩展,我不得不求助于这些方面:

foo : function() {
    mp.doCallbacks('foo_before');
    // do actual stuff, maybe some hookpoints in between
    mp.doCallbacks('foo_after');        
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序中的每个功能都必须像这样开始和结束.这似乎不对.

所以,JS的巫师 - 什么呢?

Fré*_*idi 10

您可以编写一个函数,将另一个函数作为参数,并返回一个新函数,该函数调用该参数的钩子.例如:

function withCallbacks(name, func)
{
    return function() {
        mp.doCallbacks(name + "_before");
        func();
        mp.doCallbacks(name + "_after"); 
    };
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样写:

foo: withCallbacks("foo", function() {
    // Do actual stuff, maybe some hookpoints in between.
})
Run Code Online (Sandbox Code Playgroud)