[英]Javascript bind event handler of another function activating / ending
在Javascript中,是否有某种方法可以绑定和激活和终止一个函数的事件处理程序?
因此,例如,我有两个功能:
function one() { console.log("this is function one") }
和
function two() { console.log("this is function two") }
我希望函数2在调用函数1及其结束时均能激活。 显然,我可以:
function one() { two(); console.log("this is function one"); two() }
但这会很无聊-几乎没有这种方式有趣。
好吧,您可以编写一个将原始函数包装在另一个调用回调函数中的函数。
function bindStartEnd(originalFn, callback, thisArg) {
return function() {
var returnValue;
callback();
returnValue = originalFn.apply(thisArg || null, arguments);
callback();
return returnValue;
};
}
可以这样使用:
function one() {
console.log("This is function one");
}
function two() {
console.log("This is function two");
}
var three = bindStartEnd(one, two);
three();
它可以扩展为还接受两个回调,一个用于开始,一个用于结束。 您可能还会想到一个更好的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.