I had the same need for my project. The following is the object returned by the AngularJS factory (which initializes the WebSocket). The onmessage method automatically unsubscribes the callback if you pass its associated scope in the second argument.
io = onmessage: (callback, scope) -> listeners.push callback if scope then scope.$on "$destroy", => @offmessage callback offmessage: (callback) -> listeners.remove callback
The following is the equivalence of JavaScript.
var io = { onmessage: function(callback, scope) { var _this = this; listeners.push(callback); if (scope) { scope.$on("$destroy", function() { _this.offmessage(callback); }); } }, offmessage: function(callback) { listeners.remove(callback); } };
source share