gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:35:22 25 4
gpt4 key购买 nike

所以,我正在编写一个网络应用程序。几乎所有的事情都是在客户端完成的,服务器只是一个 RESTful 接口(interface)。我使用 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);

很简单,对吧?

现在,我们能够从应用程序范围内和外部注册(多个、分层的)回调。

让我烦恼的是:为了让整个事情尽可能地可扩展,我不得不求助于这些方面的东西:

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

我的应用程序中的每个函数都必须这样开始和结束。这似乎不对。

那么,SO 的 JS 向导 - 做什么?

最佳答案

您可以编写一个函数,该函数将另一个函数作为参数,并返回一个围绕该参数调用 Hook 的新函数。例如:

function withCallbacks(name, func)
{
return function() {
mp.doCallbacks(name + "_before");
func();
mp.doCallbacks(name + "_after");
};
}

然后你可以这样写:

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

关于javascript - 使用 JS/jQuery 以编程方式实现回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7615252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com