Reputation: 5535
I can't find a nice way to pass additional parameters to socket.io 'on' handler, i.e.:
var someEventHandler = require('someEventHandler'),
additionalData = {test: 1};
socket.on('event', someEventHandler);
Now I want to access additionalData object inside someEventHandler function which is located in another file. Is there a similar way to pass arguments to handlers like jQuery 'on' gives us? ( $obj.on('event', '.selector', dataObject, handlerFunction)
)
Upvotes: 3
Views: 2806
Reputation: 3389
Since you don't like wrapping the callback yourself, you can change the socket.on
function to make it match your desires. Something like
const originalOn = socket.on;
socket.on = function (event, data, callback) {
return originalOn.call(socket, event, (e) => callback(e, data));
};
You can now use it like so:
let data = {/* important data */};
socket.on('importantEvent', data, (e, additionalData) => {
// Have fun with your data
});
Upvotes: 1
Reputation: 11397
You can use another function to handle the event, which then passes whatever additional data you need. Example:
var someEventHandler = require('someEventHandler'),
additionalData = {test: 1};
socket.on('event', function(e) { someEventHandler(e, additionalData); } );
Upvotes: 4