Can someone please explain the code snippet below to me? I found it on this website:
http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets
Snippet from Factory:
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
Snippet from Controller:
function AppCtrl($scope, socket) {
// Socket listeners
// ================
socket.on('init', function (data) {
$scope.name = data.name;
$scope.users = data.users;
});
$scope.sendMessage = function () {
socket.emit('send:message', {
message: $scope.message
});
// add the message to our model locally
$scope.messages.push({
user: $scope.name,
text: $scope.message
});
// clear message box
$scope.message = '';
};
}
My questions are:
What happens after the controller triggers
? The factory'ssocket.on('init',function(data){.....});
socket.on
method takes two parameters - eventName and callback. What does this callback function do?Why is
$rootScope.apply
being used?Can you explain what
callback.apply
does?