问题描述
var f = function() {
// Do something useful here
};
有没有一种方法可以观察"此功能,并在执行该功能时得到通知?类似于jQuery中的 bind ,但是我想 bind 函数而不是dom事件?
Is there a way to 'observe' this function, and get notified when it is executed? Something similar to bind in jQuery, but I want to bind functions and not dom events?
我不想要这样的东西:
var f = function() {
// Do something useful here
notifyObserver();
};
但我想要是这样的:
f.bind(function() {
alert('F was executed.');
});
推荐答案
您可以将f替换为调用notifyObserver的函数:
You could replace f with a function that calls notifyObserver:
f = (function(oldF){
return function(){
notifyObserver();
oldF();
};
})(f);
那样,您无需修改(旧的)f本身.当然,这不包括您的 bind
功能.我可能为此创建了某种管理器类,您可以在其中注册事件处理程序
That way you don't need to modify (the old) f itself. This doesn't include your bind
functionality, of course. I'd probably create some kind of manager class for this where you can register event handlers
manager.bind('f', function(){...});
创建包装器函数看起来更像
And creating the wrapper function would look more like
f = (function(oldF){
return function(){
manager.notify('f');
oldF();
};
})(f);
您可以概括包装器的创建:
You can generalize the creation of the wrapper:
function wrap(methodToWrap, eventName){
return function(){
manager.notify(eventName);
return methodToWrap.apply(this, arguments);
}
}
(这可用于任意数量的参数和返回值!)
(This works with any number of arguments and return values!)
然后执行以下操作:
f = wrap(f, "f");
请参阅: http://jsfiddle.net/NBefc/2/(已更新,没有返回值)
See: http://jsfiddle.net/NBefc/2/ (updated, no with return values)
这篇关于执行功能时通知jQuery/Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!