Created
February 5, 2014 00:38
-
-
Save Vitaliy-Yarovuy/8815316 to your computer and use it in GitHub Desktop.
angular.js with socket.io integration
This file contains 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
'use strict'; | |
app.factory('socket',function ($rootScope){ | |
var socket = io.connect(); | |
return { | |
on: function (eventName,callback){ | |
socket.on(eventName,function(){ | |
var args = [].slice.call(arguments); | |
$rootScope.$apply(function(){ | |
if(callback){ | |
callback.apply(socket,args); | |
} | |
}); | |
}); | |
}, | |
emit: function (eventName, data, callback){ | |
var args = [].slice.call(arguments), cb; | |
if( typeof args[args.length-1] == "function" ){ | |
cb = args[args.length-1]; | |
args[args.length-1] = function(){ | |
var args = [].slice.call(arguments); | |
$rootScope.$apply(function(){ | |
if(cb){ | |
cb.apply(socket,args); | |
} | |
}); | |
}; | |
} | |
socket.emit.apply(socket, args); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment