0

我有很多场景需要点击等来触发页面上另一个位置的行为(单向通信场景)。我现在需要双向通信,在元素 A 中发生的事情可以修改元素 B 后面范围内的特定属性,反之亦然。到目前为止,我一直在使用$rootScope.$broadcast它来促进这一点,但感觉有点矫枉过正,最终在两个地方都创建了样板:

$scope.$on('event-name', function(event, someArg) {
    if(someArg === $scope.someProperty) return;

    $scope.someProperty = someArg;
});

$scope.$watch('someProperty', function(newValue) {
    $rootScope.$broadcast('event-name', newValue);
});

有没有更好的办法?我想通过一个服务将两个(或三个,或 N 个)范围联系在一起,但如果没有魔术事件名称和样板,我看不出有办法做到这一点。

4

2 回答 2

1

我自己没有使用过这个,但这篇文章基本上解释了我将如何做到这一点。这是说明这个想法的代码:

(function() {
    var mod = angular.module("App.services", []);

    //register other services here...

    /* pubsub - based on https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js*/
    mod.factory('pubsub', function() {
        var cache = {};
        return {
            publish: function(topic, args) { 
                cache[topic] && $.each(cache[topic], function() {
                    this.apply(null, args || []);
                });
            },

            subscribe: function(topic, callback) {
                if(!cache[topic]) {
                    cache[topic] = [];
                }
                cache[topic].push(callback);
                return [topic, callback]; 
            },

            unsubscribe: function(handle) {
                var t = handle[0];
                cache[t] && d.each(cache[t], function(idx){
                    if(this == handle[1]){
                        cache[t].splice(idx, 1);
                    }
                });
            }
        }
    });


    return mod;
})();

如果控制器在没有取消订阅的情况下被“删除”,请注意内存泄漏。

于 2013-04-26T11:54:58.433 回答
0

我认为您可以尝试以下服务,

'use strict';
angular.module('test')
  .service('messageBus', function($q) {
    var subscriptions = {};
    var pendingQuestions = [];

    this.subscribe = function(name) {
      subscriptions[name].requestDefer = $q.defer();
      return subscriptions[name].requestDefer.promise; //for outgoing notifications
    }

    this.unsubscribe = function(name) {
      subscriptions[name].requestDefer.resolve();
      subscriptions[name].requestDefer = null;
    }

    function publish(name, data) {
      subscriptions[name].requestDefer.notify(data);
    }

    //name = whom shd answer ?
    //code = what is the question ?
    //details = details abt question.
    this.request = function(name, code, details) {
      var defered = null;
      if (subscriptions[name].requestDefer) {
        if (pendingQuestions[code]) {
          //means this question is already been waiting for answer.
          //hence return the same promise. A promise with multiple handler will get 
          //same data.
          defered = pendingQuestions[code];
        } else {
          defered = $q.defer();
          //this will be resolved by response method.
          pendingQuestions[code] = defered;
          //asking question to relevant controller
          publish(name, {
            code: code,
            details: details
          });
        }
      } else {
        //means that one is not currently in hand shaked with service.
        defered = $q.defer();
        defered.resolve({
          code: "not subscribed"
        });
      }
      return defered.promise;
    }

    //data = code + details
    //responder does not know the destination. This will be handled by the service using 
    //pendingQuestions[] array. or it is preemptive, so decide by code.
    this.response = function(data) {
      var defered = pendingQuestions[data.code];
      if (defered) {
        defered.resolve(data);
      } else {
        //means nobody requested for this.
        handlePreemptiveNotifications(data);
      }
    }

    function handlePreemptiveNotifications() {
      switch (data.code) {
        //handle them case by case
      }
    }
  });

这可以用作多控制器通信中的消息总线。它利用了 Promise API 的 Angular notify() 回调。所有参与的控制器都应该按如下方式订阅服务,

angular.module('test')
  .controller('Controller1', function($scope, messageBus) {
    var name = "controller1";

    function load() {
      var subscriber = messageBus.subscribe(name);
      subscriber.then(null, null, function(data) {
        handleRequestFromService(data);
      });
    }

    function handleRequestFromService(data) {
      //process according to data content
      if (data.code == 1) {
        data.count = 10;
        messageBus.respond(data);
      }
    }

    $scope.$on("$destroy", function(event) {
      //before do any pending updates
      messageBus.unsubscribe(name);
    });

    load();
  });

angular.module('test')
  .controller('Controller2', function($scope, messageBus) {
    var name = "controller2";

    function load() {
      var subscriber = messageBus.subscribe(name);
      subscriber.then(null, null, function(data) {
        handleRequestFromService(data);
      });
    }

    function handleRequestFromService(data) {
      //process according to data content
    }

    $scope.getHorseCount = function() {
      var promise = messageBus.request("controller1", 1, {});
      promise.then(function(data) {
        console.log(data.count);
      });
    }

    $scope.$on("$destroy", function(event) {
      //before do any pending updates
      messageBus.unsubscribe(name);
    });

    load();
  });

于 2015-12-01T10:38:55.907 回答