当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 详解AngularJS的通信机制

详解AngularJS的通信机制

2018年06月18日  | 移动技术网IT编程  | 我要评论

现在几乎满世界的人都在问! 外面有人么? 这里是 uss angularjs, 我们遇到麻烦了,我们的服务讲得是克灵贡语(klingon) 而我们的控制器不能同它们的ferengi 指令通信了. 有人能帮助我们么!

我已经不知道有多少次遇到这种有关什么才是angularjs里面的组件通信的最佳方式这样的问题了. 很多时候答案都会是为此使用 $rootscope 对象去向任何想要收听的人广播$broadcast出一条消息. 然而,那还真不是做这件事的最佳方式. 组件之间广播消息意味着它们需要多少知道一些其它组件编码的细节,这样就限制了它们的模块化和重用.

本文我就将展示如何为angularjs中的内部组件通信使用发布/订阅模式.


angularjs 有多种方式可供你用于组件之间的通信,而最常使用的方法却需要你知道太多有关那些组件如何通信的细节,这样就增加了组件之间的耦合度,并降低了它们的模块性和内聚程度. 这样也就使得你的组件很难在其它应用程序中重用.

通过使用发布/订阅设计模式,我们可以降低组件之间的耦合度,并将它们的之间通信的细节封装起来. 这将能帮助增加你组件的模块化程度,可测试性以及可重用性.

我将会描述的发布/订阅模式实现由 eric burley, @eburley 在它的帖子中推荐过。

我所描述的示例应用程序,会向你展示你可以将发布/订阅模式如何运用于内部控制器通信以及控制器的服务通信. 你可以在github上我的资源库 下面找到源代码.
 
首先我们需要一条通信管道

首先我们来讲讲用于处理发布和订阅信息的服务。我定义了一个服务接口,提供了发布和订阅信息的方法,我们可以用它来处理我们想要用来交换的信息。

在下面的代码中,我定义了两个内部信息; _edit_data_, 用来表示我们需要编辑跟随信息传过来的数据,和 _data_updated_, 用来表示我们的数据已经被改变。这些都是定义在内部的,用户没办法访问到它们的,这样有助于隐藏具体实现。

而对于每条信息,有两个方法; 一个用来发布信息推送给订阅者,另一个可以让订阅者注册一个回调方法,当接收到信息的时候,这个方法就会被调用。


用来向订阅者发布信息方法是 editdata,在第 9 行,还有 dataupated,在第 19 行。它们通过 $rootscope.$broadcast 方法向待处理事件推送私有通知。

用来注册事件的方法,通过 $scope.$on 建立监听,当接收到广播的消息之后,就会轮流执行那些被订阅者注册到服务上的事件。同时,由于订阅者需要自己的 scope 作为参数传过来,我们可以用它来执行监听的信息,从而避免了维护监听者列表这些复杂的处理。注册事件的方法是 oneditdata,在 13 行,还有 ondataupdated 在 23 行。

为了隐藏实现细节,我用了 revealing module (揭示模块:好丑的名字)模式,只返回那些我希望让用户使用的方法。
 

angular.module(['application.services'])
  // define the request notification channel for the pub/sub service
  .factory('requestnotificationchannel', ['$rootscope', function ($rootscope) {
    // private notification messages
    var _edit_data_ = '_edit_data_';
    var _data_updated_ = '_data_updated_';
 
    // publish edit data notification
    var editdata = function (item) {
      $rootscope.$broadcast(_edit_data_, {item: item});
    };
    //subscribe to edit data notification
    var oneditdata = function($scope, handler) {
      $scope.$on(_edit_data_, function(event, args) {
        handler(args.item);
      });
    };
    // publish data changed notification
    var dataupdated = function () {
      $rootscope.$broadcast(_data_updated_);
    };
    // subscribe to data changed notification
    var ondataupdated = function ($scope, handler) {
      $scope.$on(_data_updated_, function (event) {
        handler();
      });
    };
    // return the publicly accessible methods
    return {
      editdata: editdata,
      oneditdata: oneditdata,
      dataupdated: dataupdated,
      ondataupdated: ondataupdated
    };
  }])

发布消息

发布消息很简单,首先我们需要在我们的控制器里为 requestnotificationchannel 引入一些依赖. 你可以在下面dataservice的定义第二行看到这个. 当事件发生时,如果需要向需要了解有变化发生的其它对象发送信号, 你只需要调用requestnotificationchannel上恰当的通知方法就可以了. 如果你注意到了dataservice的 savehop, deletehop 和 addhop 方法, 你就会看到它们都调用了 requestnotificationchannel 上的dataupdated方法, 这个方法将会给侦听器发送信号,侦听器则已经用 ondataupdated 方法注册过了.

  // define the data service that manages the data
  .factory('dataservice', ['requestnotificationchannel', function (requestnotificationchannel) {
    // private data
    var hops = [
      { "_id": { "$oid": "50ae677361d118e3646d7d6c"}, "name": "admiral", "origin": "united kingdom", "alpha": 14.75, "amount": 0.0, "use": "boil", "time": 0.0, "notes": "bittering hops derived from wye challenger. good high-alpha bittering hops. use for: ales aroma: primarily for bittering substitutions: target, northdown, challenger", "type": "bittering", "form": "pellet", "beta": 5.6, "hsi": 15.0, "humulene": 0.0, "caryophyllene": 0.0, "cohumulone": 0.0, "myrcene": 0.0, "substitutes": ""} ,
      { "_id": { "$oid": "50ae677361d118e3646d7d6d"}, "name": "ahtanum", "origin": "u.s.", "alpha": 6.0, "amount": 0.0, "use": "boil", "time": 0.0, "notes": "distinctive aromatic hops with moderate bittering power from washington. use for: distinctive aroma substitutes: n/a", "type": "aroma", "form": "pellet", "beta": 5.25, "hsi": 30.0, "humulene": 0.0, "caryophyllene": 0.0, "cohumulone": 0.0, "myrcene": 0.0, "substitutes": ""} ,
      { "_id": { "$oid": "50ae677361d118e3646d7d6e"}, "name": "amarillo gold", "origin": "u.s.", "alpha": 8.5, "amount": 0.0, "use": "boil", "time": 0.0, "notes": "unknown origin, but character similar to cascade. use for: ipas, ales aroma: citrus, flowery substitutions: cascade, centennial", "type": "aroma", "form": "pellet", "beta": 6.0, "hsi": 25.0, "humulene": 0.0, "caryophyllene": 0.0, "cohumulone": 0.0, "myrcene": 0.0, "substitutes": ""} ,
      { "_id": { "$oid": "50ae677361d118e3646d7d6f"}, "name": "aquila", "origin": "u.s.", "alpha": 6.5, "amount": 0.0, "use": "boil", "time": 0.0, "notes": "aroma hops developed in 1988. limited use due to high cohumolone.used for: aroma hops substitutes: clusterno longer commercially grown.", "type": "aroma", "form": "pellet", "beta": 3.0, "hsi": 35.0, "humulene": 0.0, "caryophyllene": 0.0, "cohumulone": 0.0, "myrcene": 0.0, "substitutes": ""} ,
      { "_id": { "$oid": "50ae677361d118e3646d7d70"}, "name": "auscha (saaz)", "origin": "czech republic", "alpha": 3.3, "amount": 0.0, "use": "boil", "time": 0.0, "notes": " use for: pilsners and bohemian style lagers aroma: delicate, mild, clean, somewhat floral -- noble hops substitute: tettnanger, lublinexamples: pulsner urquell", "type": "aroma", "form": "pellet", "beta": 3.5, "hsi": 42.0, "humulene": 0.0, "caryophyllene": 0.0, "cohumulone": 0.0, "myrcene": 0.0, "substitutes": ""} ,
    ];
    // sends notification that data has been updated
    var savehop = function(hop) {
      requestnotificationchannel.dataupdated();
    };
    // removes the item from the array and sends a notification that data has been updated
    var deletehop = function(hop) {
      for(var i = 0; i < hops.length; i++) {
        if(hops[i]._id.$oid === hop._id.$oid) {
          hops.splice(i, 1);
          requestnotificationchannel.dataupdated();
          return;
        }
      };
    };
    // internal function to generate a random number guid generation
    var s4 = function() {
      return (((1+math.random())*0x10000)|0).tostring(16).substring(1);
    };
    // generates a guid for adding items to array
    var guid = function () {
     return (s4() + s4() + "-" + s4() + "-4" + s4().substr(0,3) + "-" + s4() + "-" + s4() + s4() + s4()).tolowercase();
    };
    // function to add a hop to the array and sends a notification that data has been updated
    var addhop = function(hop) {
      hops.id.$oid = guid();
      hops.push(hop);
      requestnotificationchannel.dataupdated();
    };
    // returns the array of hops
    var gethops = function() {
      return hops;
    };
    // returns a specific hop with the given id
    var gethop = function(id) {
      for(var i = 0; i < hops.length; i++) {
        if(hops[i]._id.$oid === id) {
          return hops[i];
        }
      };
    };
    // return the publicly accessible methods
    return {
      gethops: gethops,
      gethop: gethop,
      savehop: savehop,
      deletehop: deletehop,
      addhop: addhop
    }
  }]);

 
接收事件通知

从 requestnotificationchannel 接收事件通知也很简单,额外的我们只需要回调处理器来在消息被发送时使用通知来做一些自己的处理. 我们将再次需要添加一些依赖到面向我们的控制器、服务以及指令的 requestnotificationchannel 上, 你可以在下面代码的第二行中看到这些. 接下来我们需要定义一个事件回调处理器来对事件通知做出回应,你可以在下面的第五行代码中看到. 然后我们需要通过调用 ondataupdated 方法来吧我们的回调处理器注册到requestnotificationchannel,并传入来自控制器和回调处理器的范围, 我们在第9行代码中做了这些事情.

 

  //define the controller for view1
  .controller('view1-controller', ['$scope', 'dataservice', 'requestnotificationchannel', function($scope, dataservice, requestnotificationchannel) {
    $scope.hops = dataservice.gethops();
 
    var ondataupdatedhandler = function() {
      $scope.hops = dataservice.gethops();
    }
 
    requestnotificationchannel.ondataupdated($scope, ondataupdatedhandler);
 
    $scope.onedit = function(hop) {
      requestnotificationchannel.editdata(hop);
    }
 
    $scope.ondelete = function(hop) {
      dataservice.deletehop(hop);
    }
  }]);

用于控制器通信的控制器

我们也可以将 the requestnotificationchannel 用于控制器间的通信. 我们只需要有一个控制器扮演发布者的角色,而另外一个控制器扮演订阅者的角色就行了. 如果你观察到前段代码第11行view1-controller的onedit方法,你会看到它发送了一个editdata消息,消息包含需要使用 requestnotificationchannel 编辑的项.  下面的 view2-controller 从第5行到第9行将它的 oneditdatahandler 用 requestnotificationchannel 进行了注册. 如此无论何时view1-controller一旦发送editdata消息,带上要修改的项,view2-controller都会受到editdata消息的通知,获得该项并将其更新到它的模型.
 

  //define the controller for view1
  .controller('view2-controller', ['$scope', 'dataservice', 'requestnotificationchannel', function($scope, dataservice, requestnotificationchannel) {
    $scope.hop = null;
 
    var oneditdatahandler = function(item) {
      $scope.hop = item;
    };
 
    requestnotificationchannel.oneditdata($scope, oneditdatahandler);
 
    $scope.onsave = function() {
      dataservice.savehop($scope.hop);
      $scope.hop = null;
    }
 
    $scope.oncancel = function() {
      $scope.hop = null;
    }
  }]);

写一个好的接口文档

有一件事情可能会被忽略,我们在组件间用了通信接口,而这些接口,它们需要一个好的文档来说明应当如何使用。上面的例子中,如果没有文档,用户肯定不会知道 oneditdata 会给回调函数传一个待编辑数据。所以当你开始用这个模式,用好的技巧在于,给方法写注释文档,以确保通知服务明确知道发生了什么事情。
总结

好了,我们探讨了如何在你的 angularjs 应用中使用订阅/发布模式来实现模块间通信。该模式可以让你的模块从内部消息解耦,更便于复用。你甚至可以把模块之间的通信全部替换成订阅/发布模式。尤其当你的服务中有很多异步请求,以及你希望把数据缓存在服务中,从而减少和服务器通信的时候,这种模式相当有效。

我希望这对你有所帮助,你可以在我的 github 仓库 下找到例子的代码。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网