jQuery(或干净的 JS)- 向任何函数参数添加回调
jQuery (or clean JS) - add callback to any function-parameter
我想要的是这样的:
function bindFunctions(bindFunction, callbackFunction) {
// Add binding so that I can call the callbackFunction if the bindFunction is called
}
function log(message) {
console.log(message);
}
function notifyUser() {
alert('Something');
}
bindFunctions(log, notifyUser);
log('Error'); // Now the notifyUser-functions should be called and "Something" printed to the alert-box
bindFunctions($('.element').click, function() {/* CODE */}); // Or this: but I don't know if this is even possible because this is not the event-function but the binding-function of the click-event
重要提示:我对bindFunction
没有影响,所以不可能在那里实现触发器。
它是任何一种现有函数的回调的附件。您知道如何或是否可行吗?
向函数添加回调的方法是这样的:
var foo = function(number, callback){
number += 2;
callback(number);
}
foo(2, function(result){
window.alert(result)
});
https://jsfiddle.net/6dpz88md/
祝你好运
我相信你看错了。你需要的是一些好的旧 dependency inversion. Whatever code needs log
has to receive it from a higher-level component (e.g. the composition root of your application). You're then free to implement a straightforward wrapper that calls notifyUser
and inject 它而不是实际的 log
.
我链接了一些从 OO 角度出发的文章,但您可以随意转换为更实用的模型(这些方法是等效的)。在您的情况下,您正在使用闭包(在某种程度上,"equivalent" 到具有单个匿名方法的对象)。
我想要的是这样的:
function bindFunctions(bindFunction, callbackFunction) {
// Add binding so that I can call the callbackFunction if the bindFunction is called
}
function log(message) {
console.log(message);
}
function notifyUser() {
alert('Something');
}
bindFunctions(log, notifyUser);
log('Error'); // Now the notifyUser-functions should be called and "Something" printed to the alert-box
bindFunctions($('.element').click, function() {/* CODE */}); // Or this: but I don't know if this is even possible because this is not the event-function but the binding-function of the click-event
重要提示:我对bindFunction
没有影响,所以不可能在那里实现触发器。
它是任何一种现有函数的回调的附件。您知道如何或是否可行吗?
向函数添加回调的方法是这样的:
var foo = function(number, callback){
number += 2;
callback(number);
}
foo(2, function(result){
window.alert(result)
});
https://jsfiddle.net/6dpz88md/
祝你好运
我相信你看错了。你需要的是一些好的旧 dependency inversion. Whatever code needs log
has to receive it from a higher-level component (e.g. the composition root of your application). You're then free to implement a straightforward wrapper that calls notifyUser
and inject 它而不是实际的 log
.
我链接了一些从 OO 角度出发的文章,但您可以随意转换为更实用的模型(这些方法是等效的)。在您的情况下,您正在使用闭包(在某种程度上,"equivalent" 到具有单个匿名方法的对象)。