Skip to content

Instantly share code, notes, and snippets.

@melloc01
Created March 16, 2016 23:06
Show Gist options
  • Save melloc01/47ec9200cabd9ca80de4 to your computer and use it in GitHub Desktop.
Save melloc01/47ec9200cabd9ca80de4 to your computer and use it in GitHub Desktop.
AngularJS Service
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