Last active
August 29, 2015 13:56
-
-
Save anton000/8928158 to your computer and use it in GitHub Desktop.
Socketio wrapper directive with event handler cleaner / unlistener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App.factory('socket', ['$rootScope', | |
function($rootScope) { | |
var socket = io.connect('127.0.0.1:8080'); | |
return { | |
on: function(eventName, callback) { | |
//set up callback wrapper temp var so we can return it later | |
var temp = function() { | |
var args = arguments; | |
$rootScope.$apply(function() { | |
callback.apply(socket, args); | |
}); | |
}; | |
socket.on(eventName, temp); | |
//return wrapper | |
return temp; | |
}, | |
off: function(eventName, callback) { | |
socket.removeListener(eventName, callback); | |
}, | |
emit: function (eventName, data, callback) { | |
socket.emit(eventName, data, function () { | |
var args = arguments; | |
$rootScope.$apply(function () { | |
if (callback) { | |
callback.apply(socket, args); | |
} | |
}); | |
}) | |
}, | |
socket: socket.socket | |
}; | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment