0

Is there a way to globally and automatically modify a message before emitting it? Something along the lines of jQuery ajax's beforeSend.

Right now, I'm manually adding a timestamp to the payload for each emit and it would be much less error-prone to have that done automatically.

Thanks!

lastoneisbearfood
  • 3,955
  • 5
  • 26
  • 25

1 Answers1

0

You can either override the .emit() method (saving the original so you can call it) or if you control all the code that calls .emit(), then just make your own method that adds the timestamp to the payload and then calls .emit().

To patch the original .emit(), you could do this:

(function() {
    var origEmit = Socket.prototype.emit;
    Socket.prototype.emit = function(msg, data) {
        if (typeof data === "object") {
            data.timeStamp = Date.now();
        }
        return origEmit.apply(this, arguments);
    }
})();

To create your own emit method that all your code could use, you could do this:

 Socket.prototype.emitT = function(msg, data) {
    if (typeof data === "object") {
        data.timeStamp = Date.now();
    }
    return this.emit.apply(this, arguments);
 }
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Yes, looks like it has to be this way at this point. I was hoping for a built-in hook to avoid having to do monkey patching or writing wrapper function. – lastoneisbearfood Oct 14 '14 at 05:36