$ 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.$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
'Programming' 카테고리의 다른 글
내 웹 사이트에서 Adblock을 감지하는 방법은 무엇입니까? (0) | 2020.03.01 |
---|---|
JavaScript에서 증가 (“++”) 및 감소 (“-”) 연산자를 피해야하는 이유는 무엇입니까? (0) | 2020.03.01 |
ViewModel의 INotifyPropertyChanged와 DependencyProperty (0) | 2020.03.01 |
IEnumerable로 단일 항목 전달 (0) | 2020.03.01 |
Eclipse-행 번호 속성이 누락되어 중단 점을 설치할 수 없습니다. (0) | 2020.03.01 |