I've been reading up on event passing in Angularjs and I'm not convinced that using $broadcast is a good idea.
Blogs like this one advocate getting used to $on even though it "felt like overkill."
My confusion is that the implementation uses a depth-first traversal of the scopes and looks for subscribers, which makes the speed of your events dependent on your tree structure.
Here is some code from that in angular:
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
Additionally, it seems like you would be able to hack dependency injection using these methods.
The alternative is simply a service that caches event types and callbacks, and calls them directly. This requires that you clean up the subscriptions to avoid leaks.
My question is, is there anything I'm missing about the motivation for the $broadcast/$on paradigm? Or is there any benefit to use it over a more traditional pubsub?
Let me know if I'm not being clear enough with my question, and thanks for your time.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…