繁体   English   中英

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没有影响,所以不可能在那里实现触发器。

它是任何类型现有函数的回调的附件。 你知道如何或是否可能吗?

我相信你看错了。 你需要的是一些好的旧依赖倒置 无论代码需要log都必须从更高级别的组件(例如应用程序的组合根)接收它。 然后你可以自由地实现一个简单的包装器,它调用notifyUser注入它而不是实际的log

我已经链接了一些从面向对象的角度来看的文章,但可以随意转换为更实用的模型(方法是等效的)。 在您的情况下,您使用的是闭包(在某些情况下,它们“等同于”具有单个匿名方法的对象)。

向函数添加回调的方法是:

var foo = function(number, callback){
    number += 2;
    callback(number);
}

foo(2, function(result){
    window.alert(result)
});

https://jsfiddle.net/6dpz88md/

祝你好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM