Created
March 16, 2016 23:06
-
-
Save melloc01/47ec9200cabd9ca80de4 to your computer and use it in GitHub Desktop.
AngularJS Service
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
function BindSocketService($rootScope, io) { | |
function BindSocket(resource, items) { | |
var connection = io.socket.on(resource,function handle(evt) { | |
switch (evt.verb) { | |
case 'created': | |
items.push(evt.data); | |
$rootScope.$apply(); | |
break; | |
case 'destroyed': | |
var index; | |
items.map(function (user, i) { | |
if (user.id == evt.id) | |
index = i; | |
}); | |
items.splice(index, 1); | |
$rootScope.$apply(); | |
break; | |
case 'updated': | |
items.map(function (user, i) { | |
if (user.id == evt.id) | |
for (var key in evt.data) | |
if (evt.data.hasOwnProperty(key)) | |
user[key] = evt.data[key]; | |
return user; | |
}); | |
$rootScope.$apply(); | |
break; | |
} | |
}); | |
$rootScope.$broadcast('socket.io.connection', connection); | |
return connection; | |
} | |
return BindSocket; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment