Tiago Espinha
Tiago Espinha

Reputation: 1209

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:

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:

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.

Upvotes: 1

Views: 1036

Answers (2)

user943702
user943702

Reputation: 954

// 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
});

Upvotes: 4

BuddhiP
BuddhiP

Reputation: 6451

Consider using the jQuery Deferred object, and adding a method to execute 'always'

jQuery Deferred Object Documentation

Upvotes: 1

Related Questions