Search code examples
javascriptobserver-pattern

Javascript Observer Pattern


I am fairly new to design patterns and I came across this website that explains observer pattern

import { ToastContainer, toast } from "react-toastify";

function logger(data) {
  console.log(`${Date.now()} ${data}`);
}

function toastify(data) {
  toast(data);
}

observable.subscribe(logger);
observable.subscribe(toastify);

export default function App() {
  function handleClick() {
    observable.notify("User clicked button!");
  }

  function handleToggle() {
    observable.notify("User toggled switch!");
  }

  return (
    <div className="App">
      <Button>Click me!</Button>
      <FormControlLabel control={<Switch />} />
      <ToastContainer />
    </div>
  );
}

My Question:- I don't understand why do we need to write this extra line observable.notify("User clicked button!"); inside the handleClick function and observable.notify("User toggled switch!"); inside the handleToggle function.

My Naive Approach:- We could have simply invoked logger function from within the handleClick function something like

function handleClick(){
return logger('User clicked button')
} 

I know that observable.subscribe(logger); and observable.subscribe(toastify); have been used so we need to use the notify() method but can't all these be handled using simpple function invokations what's the whole point of using it like this ?

Sanbox Link from the website

Any example references would much be appreciated.


Solution

  • We could have simply invoked logger function from within the handleClick function...

    Yes, but the purpose of the Observer pattern is to decouple the publishing code from the subscriber code. The publishing code just knows that it needs to publish the event, and provide the relevant data for the event. It doesn't have any specific knowledge of the subscribers. It's that decoupling that's the point of the pattern.

    (Separately, just as a pragmatic point, if you made that change, you would no longer be calling toast. You'd only be calling logger.)