【问题标题】:What's the best practice to do event driven development in Angular.js apps?在 Angular.js 应用程序中进行事件驱动开发的最佳实践是什么?
【发布时间】:2013-03-04 21:24:36
【问题描述】:

我正在向我们的 Angular 应用程序添加一些 websocket 功能。 Websocket 对象被包装在一个服务中。理想情况下,我们希望我们封装的套接字对象有一个标准的事件 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  

我们实现这一目标的最佳做法/库是什么?使用jQuery? Backbone.Events?任何建议都会有所帮助。谢谢!

【问题讨论】:

    标签: javascript angularjs event-driven event-driven-design


    【解决方案1】:

    您不需要使用任何库来实现这一点,只需创建一个服务,注入 $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();
      };
    });
    

    【讨论】:

    • 感谢您对 fastreload 的回答,但这并不是我所需要的。在我的示例中,控制器只能为自己取消订阅套接字消息,换句话说,订阅是基于控制器的粒度 - 每个控制器可以决定何时订阅和何时取消订阅。想法?
    • 感谢 fastreload。这不是一个糟糕的解决方案。
    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2010-10-14
    • 2019-08-22
    相关资源
    最近更新 更多