Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - Angularjs pubsub vs $broadcast

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think you are missing anything. You've successfully outlined the pros/cons of each approach.

The $broadcast/$on approach doesn't require you to unsubscribe, but it is not terribly efficient as it broadcasts to all the scopes. It also has a very low barrier to entry. You don't need to inject any services, you don't need to create them. They broadcast to everyone, so it is a more simple approach.

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. It is more complex, however, because you need to write your service with callback handlers, and you have to remember to unsubscribe. The remembering to unsubscribe is pretty huge in my opinion. If you don't get this right, you get memory leaks. And you won't know it until it is a problem in 3 months.

I can see why the built-in approach is $broadcast.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...