我需要一些帮助来理解下面的代码。摘自:
http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets
工厂:
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);
}
});
})
}
};
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 = '';
};
}
我的疑问是:
一旦 Controller 调用
socket.on('init',function(data){.....});
,控制流程是怎样的。在工厂中,当调用socket.on
时,它需要两个参数eventName和callback。这个回调是什么?为什么我们使用
$rootScope.apply
什么是
callback.apply
?
最佳答案
1.What is the flow of control once the controller calls socket.on('init',function(data){.....});. In factory when socket.on is called it takes two parameters eventName and callback. What is this callback?
调用 socket.on
并没有什么特别之处。从您的 Controller 。这样做只需调用 on
直接在工厂中的方法。
一旦清楚了,就很容易看出 callback
只是传递给该函数的第二个参数。在此示例中,它是函数 function (data) { $scope.name = data.name; $scope.users = data.users; }
2.Why are we using $rootScope.apply
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply
确保函数内部发生的任何事情都会在摘要循环中被拾取。
3.What is callback.apply?
这是 apply method它存在于任何 JavaScript 函数中。这里用它来调用 callback
套接字为this
参数和事件处理程序的参数作为参数。
关于javascript - AngularJs 工厂和 Controller 控制流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33032965/