I am building a middleware layer between my Socket.IO events and the rest of my application. I do this so that I can swap out Socket.IO for something else in the future.
I store callback functions in an array. When a specific event triggers, I loop over the array and execute the callback functions. That works like a charm.
The problem lies in the removing of a callback from that array. When a callback function needs to be removed, I loop over the array and check every array item to see if it is equal (using ===
) to the callback I want to remove. When just the callback is stored in the array, this works fine. However, when a callback is stored in combination with .bind()
, the equal check returns false.
I created a (simplified) codepen to demonstrate the problem: http://codepen.io/petergoes/pen/wWPJdg?editors=0012.
I draw inspiration from the Socket.IO code to write my removal method: https://github.com/socketio/socket.io-client/blob/master/socket.io.js#L1623. However, there the same problem occurs.
The big question:
How can I compare two functions when (one or both of them) are called with the .bind()
method?
I found this answer how do I compare 2 functions in javascript. However, comparing the string version of a function feels a bit sketchy
The codepen for reference:
var callbackList = [];
var objA = {
myCallbackFunction: function myCallbackFunction() {
console.log('hello my name is:', this.myName);
}
}
var objB = {
register: function register(callback) {
console.log('register callback');
callbackList.push(callback);
},
remove: function remove(callback) {
console.log('remove callback');
if(callbackList[0] === callback) {
console.log('callback found, splice it');
callbackList.splice(0, 1);
} else {
console.log('callback NOT found!');
}
console.log('callbackList length:', callbackList.length);
}
}
objB.register(objA.myCallbackFunction.bind({myName: 'Peter'}));
objB.remove(objA.myCallbackFunction.bind({myName: 'Peter'}));
console.log('\nreset callbackList\n');
callbackList = [];
objB.register(objA.myCallbackFunction);
objB.remove(objA.myCallbackFunction);