I have a need for inter-component communication in a web application and am considering different ways to accomplish this. I have some ideas, but would welcome other ideas.
First, a quick and simple example. I have two separate components on a page that are loaded asynchronously. By component, I mean a chunk of HTML that has a javascript object associated with it that includes jquery-based behaviors on nodes in the html. When a user interacts with one component, changes should take place in the other component, and vice-versa.
The key thing to remember here is that each component should be a self-contained unit. It could be re-used in different parts of an application, or even different applications. So it doesn't know about the existence of the other components on the page.
My current thoughts on a solution involve having components listen for custom events that they are interested in as well as sending custom events when an action has taken place. Therefore, each component listens for events that are triggered by the other one.
The problem is that because of the async loading, one component might take longer to load than the other. There is a possibility that an event might get sent too soon and be lost. In some situations this might be fine, but in some cases I need to make sure that all events a component sends get consumed.
So here's some related questions:
What happens to an event after it is triggered? Does it just disappear if there are no listeners at the time it was triggered?
Is there a way to detect if a triggered even was consumed or lost?
What are some good ways for each component to know about the other components?
Are there any existing open-source javascript projects or jquery plugins that deal with these types of things?
In regards to question #3, I'm thinking that each component could send out some sort of register event that includes the types of events that it listens to and a list of components that it has registered with. Components would listen for these register events. Some sort of registration logic using timers would be used to make sure the right components get registered together during the component loading process. Once the registration has completed, then the components would be able to send their normal events.