[英]Best practice for code after callback
Here's what I'm trying to do. 这就是我想要做的。
I'm currently using node.js and one of the things it allows you to do is: 我当前正在使用node.js,它允许您执行的操作之一是:
socket.on("sometopic", function() {
// this is a callback
}
Now let's say I have 10 different topics, each of these with one corresponding handling function that I keep in my "window", as such: 现在假设我有10个不同的主题,每个主题都有一个对应的处理函数,这些函数将保留在“窗口”中,如下所示:
windows.callbacks["topic_a"] = function() {
// code for cb a
}
windows.callbacks["topic_b"] = function() {
// code for cb b
}
windows.callbacks["topic_z"] = function() {
// code for cb z
}
And there's a piece of code I would like to have executed at the end of every callback . 而且我想在每个回调的末尾执行一段代码。 An easy way out is to create a function with this code and add a call at the end of each callback but this is far from being elegant.
一种简单的方法是使用此代码创建一个函数,并在每个回调的末尾添加一个调用,但这远非如此。
Can anyone suggest a better solution for this? 任何人都可以提出这个更好的解决办法? Is there a best practice that I'm unaware of?
有我不知道的最佳实践吗? I'm fairly green to this kind of functional programming.
我相当绿色这类函数式编程。
// THIS IS AN IDEA
// helper
function teardownWith(fn){
return function (cb){
return function(){
return (cb(), fn());
};
};
}
// prepare a modified function
var endWithDate = teardownWith(function(){
log(Date());
});
// pass our callback into the modified function
// endWithDate() returns the final callback.
window.callbacks["cb_a"] = endWithDate(function(){
// code for cb_a
});
Consider using the jQuery Deferred object, and adding a method to execute 'always' 考虑使用jQuery Deferred对象,并添加一种方法来“始终”执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.