Programming

$ rootScope. $ broadcast vs. $ scope. $ emit

procodes 2020. 3. 1. 16:02
반응형

$ rootScope. $ broadcast vs. $ scope. $ emit


이제 사이의 성능 차이 있음 $broadcast과이 $emit제거 된 선호 할 이유가 $scope.$emit에가 $rootScope.$broadcast?

그들은 다릅니다.

$emit 범위 계층 (위쪽)으로 제한됩니다-디자인에 맞으면 좋을 수도 있지만 다소 임의적 인 제한으로 보입니다.

$rootScope.$broadcast이벤트를 듣도록 선택한 모든 사람에 대해 작동합니다 . 이는 제 생각에보다 합리적인 제한입니다.

뭔가 빠졌습니까?

편집하다:

답변에 대한 답변으로 명확히하기 위해 디스패치의 방향은 내가 추구하는 문제가 아닙니다. $scope.$emit이벤트를 위쪽 및 $scope.$broadcast아래쪽 으로 전달합니다 . 그러나 항상 $rootScope.$broadcast모든 의도 된 청취자에게 도달하기 위해 사용하지 않는 이유 는 무엇입니까?


tl; dr (이 tl; dr은 아래 @ sp00m 의 답변입니다)

$emit이벤트를 위로 $broadcast파견 ... 이벤트를 아래로 파견

상해

$rootScope.$emit다른 $rootScope청취자 잡을 수 있습니다. 이것은 당신이 $scope그것을 얻기를 원하지 않을 때 좋습니다 . 주로 높은 수준의 커뮤니케이션. 아이들이들을 수 없도록 어른들이 방에서 서로 이야기하고 있다고 생각하십시오.

$rootScope.$broadcast거의 모든 것이들을 수있는 방법입니다. 이것은 집안의 모든 사람들이 그것을들을 수 있도록 저녁 식사가 준비되었다고 소리 치는 부모와 같습니다.

$scope.$emit당신이 그 $scope모든 부모님을 원하고 $rootScope이벤트를들을 때입니다. 이것은 집에서 부모에게 물고있는 아이입니다 (그러나 다른 아이들이들을 수있는 식료품 점에서는 아닙니다).

$scope.$broadcast을위한 $scope자신과 아이들. 부모님이들을 수없는 박제 된 동물에게 속삭이는 아이입니다.


동일한 작업을 수행하지 않습니다 . 범위 계층 구조를 통해 위쪽으로$emit 이벤트 전달하고 모든 하위 범위로 아래쪽 으로 이벤트 전달합니다 .$broadcast


다음 링크에서 다음 그래픽을 만들었습니다. https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

범위, rootScope, 방출, 브로드 캐스트

보다시피, $rootScope.$broadcast보다 많은 청취자를 공격합니다 $scope.$emit.

또한 $scope.$emit버블 링 효과는 취소 할 수 있지만 취소 $rootScope.$broadcast할 수는 없습니다.


여기에 이미지 설명을 입력하십시오

$ scope. $ emit :이 메소드는 이벤트를 위쪽에서 (자식에서 부모로) 전달합니다.

여기에 이미지 설명을 입력하십시오 $ scope. $ broadcast : 메서드는 이벤트를 아래쪽에서 (부모에서 자식으로) 모든 자식 컨트롤러로 전달합니다.

여기에 이미지 설명을 입력하십시오$ scope. $ on : 일부 이벤트를 수신하기위한 메소드 등록. 해당 이벤트를 수신하는 모든 컨트롤러는 브로드 캐스트 알림을 받거나 자식-부모 계층 구조에 맞는 위치에 따라 방출합니다.

$ emit 이벤트는 이벤트를 듣고있는 $ scope 중 하나에 의해 취소 될 수 있습니다.

$ on은 "stopPropagation"메소드를 제공합니다. 이 메소드를 호출하면 이벤트 전파가 더 이상 중지되지 않을 수 있습니다.

플 런커 : https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

형제 범위 (직접 부모-자식 계층에없는 범위)의 경우 $ emit 및 $ broadcast는 형제 범위와 통신하지 않습니다.

여기에 이미지 설명을 입력하십시오

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html


@Eddie has given a perfect answer of the question asked. But I would like to draw attention to using an more efficient approach of Pub/Sub.

As this answer suggests,

The $broadcast/$on approach is not terribly efficient as it broadcasts to all the scopes(Either in one direction or both direction of Scope hierarchy). While the Pub/Sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work.

you can use angular-PubSub angular module. once you add PubSub module to your app dependency, you can use PubSub service to subscribe and unsubscribe events/topics.

Easy to subscribe:

// Subscribe to event
var sub = PubSub.subscribe('event-name', function(topic, data){

});

Easy to publish

PubSub.publish('event-name', {
    prop1: value1,
    prop2: value2
});

To unsubscribe, use PubSub.unsubscribe(sub); OR PubSub.unsubscribe('event-name');.

NOTE Don't forget to unsubscribe to avoid memory leaks.


Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

참고URL : https://stackoverflow.com/questions/26752030/rootscope-broadcast-vs-scope-emit



반응형