Can anyone give me some advice on the pros / cons of using events heavily to keep different parts of an Angular app in sync with each other?
I am considering using a series of events and event listeners to wire together an SPA with multiple concurrent and nested views, provided by Angular's ui-router. The layout of the SPA could be analogous to gmail, where there are logically separate regions of the screen (left area with list of mail folders, top navbar, main details view, etc).
I have been looking at ways to keep all the controllers in sync with regards to models they all need to access at the same time. When a model is updated by the top view, if some of that model is displayed in the main view, I want the main view to notice the change, and update its view accordingly.
I use services to share models across controllers, as is considered the best practice, but there are issues with that approach as discussed in depth in this question.
A possible solution to this is to use Angular's $broadcast
and .$on('event, fn())
to have controllers notice when a service they care about has updated data.
Problems:
Using events to pass data instead of using services (tight coupling, ignoring any authoritative data source). I know you can pass object with events, but you don't have to.
Performance (events bubble throughout $scope hierarchy, etc).
$broadcast
/$emit
have performance and tight-coupling concerns that are covered a-plenty here and elsewhere, and I am considering using solution from an SO answer here to address performance / memory leaks from not cleaning up listeners when controllers are destroyed.Maintenance (spaghetti code / ignoring OO and just passing your entire app's model around in events). This is the main question I have for the community: based on the (ugly) diagram below, I imagine each angular
.service
firing an event when it gets updated model data, and any controllers who care about that data just listen for the event to fire:
It's actually simple to code (works now), but I worry about the 5-years-from-now headache of trying to keep track of all the event relationships.
Does anyone have any experience with a design like this, who can give me some advice on a smarter / more concise design?
Thanks in advance, and sorry for the crude diagram... hopefully its gets across the point.