所以,我正在編寫一個Web應用程序。幾乎所有事情都是在客戶端完成的,服務器只是一個RESTful接口。我使用jQuery作爲我的選擇框架,並在Revealing Module Pattern中實現我的代碼。以編程方式實現與JS/jQuery的回調
我的代碼基本上線框看起來像這樣:
(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');
}
我的應用程序內的每個單一的功能將不得不開始和結束像那樣。這看起來不正確。
那麼,JS的巫師呢 - 幹什麼?
幾乎所有的插件架構我見過的實施已採取之前和掛機後。據我所知,大多數時候你只需要實現人們所要求的內容。沒有我知道的魔術解決方案。 –
這似乎是一個過度工程的例子。你真的需要庫中的每個_internal_函數來支持回調之前和之後嗎? Rails就像一個巨大的回調三明治,即使如此,Rails中只有1%的方法支持回調。而且,在他們支持回調的地方,它們完全按照您在示例_foo_函數中所述的方式執行。 –