[英]What's the best practice to do event driven development in Angular.js apps?
I am adding some websocket functional to our angular app. 我正在为我们的角应用添加一些websocket功能。 The Websocket object is wrapped in a service.
Websocket对象包含在服务中。 Ideally we would like our wrapped socket object to have a standard event API so that we can use it in the controller like the following: (Sorry for the Coffeescript)
理想情况下,我们希望我们的包装套接字对象具有标准事件API,以便我们可以在控制器中使用它,如下所示:(抱歉Coffeescript)
angular.module('myApp').controller 'myCtrl', ($scope, socket) ->
update = (msg)->
$scope.apply ->
#do something regarding to the msg
socket.on 'message', update
unregister: ->
socket.off 'message', update
What's the best practice/library for us to achieve this? 实现这一目标的最佳实践/图书馆是什么? Use jquery?
使用jquery? Backbone.Events?
Backbone.Events? Any suggestion will be helpful.
任何建议都会有所帮助。 Thanks!
谢谢!
You don't need to use any library to achieve this, just create a service, inject $rootscope and publish the events from there to rootscope, then in your controller listen for that event. 您不需要使用任何库来实现这一点,只需创建一个服务,注入$ rootscope并将事件从那里发布到rootscope,然后在您的控制器中监听该事件。
var socket; // this be the socketio instance.
angular.module("myApp").factory("SocketHandler", function ($rootScope) {
var handler = function (msg) {
$rootScope.$apply(function () {
$rootScope.$broadcast("socketMessageReceived", msg);
});
};
socket.on("message", handler);
$rootScope.$on("unregisterSocket", function () {
socket.off("message", handler);
});
}).controller("myCtrl", function ($scope, SocketHandler) {
var listener;
var addListener = function () {
listener = $scope.$on("messageReceived", function (e, msg) {
console.log("New Message: " + msg);
}); // $on returns a registration function for the listener
};
var removeListener = function () {
if (listener) listener();
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.