大约3周前,我开始使用AngularJS,并开始编写一个简单的应用程序,它从外部库(OnReceiveMessage)获取异步数据,然后(使用角)编辑作用域,以便显示和处理消息,甚至回复该消息。首先,我开始在应用程序控制器中声明对象,它可以工作,但它是一团糟的,这不是正确的做法。我的问题是:我如何启动这个异步客户端(通过web套接字通信),并将这个库的外部功能(发送和异步接收)转换成角(范围、应答等)。
external.js
Example:
var client = new ExtClient({params}); //not setting callbacks
Client.onMessageArrived = myCallbackHandler;
var message = new ExtMessage("Hi there");
Client.send(message);
function myCallbackHandler(message) {
console.log("onMessageArrived");
}app.js
var app = angular.module('myApp', ['connectionService']);
app.controller('MainController', [ '$scope',
function($scope) {
//I want to catch the myCallbackHandler function async with the message
//and use the client.send(message) with the response...
$scope.messageTable.push({message.id, message.value}); //messageTable is bind in the view to create a table
}]);发布于 2015-12-12 13:26:23
您还可以考虑使用$broadcast()、$emit()和$on()在$scope或$rootScope上使用应用程序的不同元素之间的通信。更多信息:
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
发布于 2015-12-12 13:05:45
在这种情况下,您需要创建一个服务。
angular.module('myApp', ['connectionService'])
.factory('messageService', function() {
var client = new ExtClient({
// set your params
});
return {
listen: function(event, callback) {
/* code to register a callback on an event */
client[event] = callback;
},
push: function(id, value) {
/* code to push a message */
client.send(new ExtMessage(message));
}
};
})
.controller('MainController', ['messageService' function(messageService) {
messageService.listen('onMessageArrived', function(message) {
console.log("onMessageArrived");
});
messageService.push('some id', 'some message');
}]);https://stackoverflow.com/questions/34239842
复制相似问题