all!
Using Node/Express/Socket.IO, I wanted to refactor out identical callbacks.
I have:
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}) });
}
but want rather something like:
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback) });
}
How can I refactor out the callback? These 2 examples does not work:
Does not work 1:
var callback = function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
Does not work 2:
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback(socket, err, result)) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback(socket, err, result)) });
}
with
var callback = function(socket, err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
How can I keep my code DRY?
Frode
If you declare "does not work 1" where it has access to the socket variable it should work. That could be done like this:
io.sockets.on('connection', function(socket) {
var callback = function(err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback) });
});
It seems you tried to solve that in "does not work 2", which would work if you return a function in the callback:
var callback = function(socket) {
// Returning the callback which will be called when noteProvider is done.
// Since it's in the closure of this function it will have a reference to socket.
return function (err, result) {
if(err) {
socket.emit('err', err);
} else {
socket.emit('result', result);
}
}
}
io.sockets.on('connection', function(socket) {
socket.on('find all notes' , function() { noteProvider.findAllNotes(callback(socket)) });
socket.on('find note by id', function(id) { noteProvider.findNoteById(id, callback(socket)) });
}