Sunrise in the fog

    The Observer Model & The Pub Sub Model

    Often times, we want to have pieces of our sites react to events and triggers. Essentially, that's what both the Observer model & the Pub Sub model are supposed to help with. They allows us to have multiple elements update on one trigger.

    There's a two parts to this post. First, we'll cover what the Observer Model is. Then the big thing I wanted to cover - how it's different from the Pub Sub model.

    What is the Observer Model? Essentially, we have a subject that watches for some event (things entering the viewport, an element changing, etc). Once that event triggers, then the observers watching for that are notified and perform some action.

    Our subject has direct reference to the subscribers - the observers are directly tied to a subscriber and, when it sees an update, it notifies the observers watching it. 

    So how is it different from the Pub Sub model? Well, the in the Observer model the observers are tied directly to the subscriber. Meaning, if we have mulitple subscribers, the observers have to manually observer each one. The subscribers are directly aware of what's observing them. 

    In the Pub Sub model, those roles (publishers and subscribers) are agnostic of each other. Subscribers listen for events, and publishers will publish their events. As many different publishers can publish events, and a subscriber that watches for that event will get notified when any of those publishers emit their event. They aren't tied to a specific publisher, just the event. It offers more flexibility than the observer model that we can just add subscribers without caring about our publishers or having reference to them (helps keep code a little cleaner).

    That's it, both are pretty basic in principle. In practice, they can be a bit of work to implement. Fortunately, we typically don't have to implement our own - we just have to know what they are so we can decide what to use. There are a couple native observers in JS engines - namely the Intersection Observer and the Mutation Observer. For the Pub Sub model, there's a pretty good library called... PubSub. Not the most creative name, but it's still a super solid library.