DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

JavaScript Design Patterns - Behavioral - Observer

Image description

The observer pattern allows for the definition of one-to-many dependency between objects so that all its dependents are notified and updated automatically when one object changes state.

In this example, we are creating a simple class product that other classes can observe registering about changes in the register() method. When something is updated, the notifyAll() method will communicate with all the observers about these changes.

class ObservedProduct {
  constructor() {
    this.price = 0;
    this.actions = [];
  }

  setBasePrice(val) {
    this.price = val;
    this.notifyAll();
  }

  register(observer) {
    this.actions.push(observer);
  }

  unregister(observer) {
    this.actions.remove.filter(function (el) {
      return el !== observer;
    });
  }

  notifyAll() {
    return this.actions.forEach(
      function (el) {
        el.update(this);
      }.bind(this)
    );
  }
}

class Fees {
  update(product) {
    product.price = product.price * 1.2;
  }
}

class Profit {
  update(product) {
    product.price = product.price * 2;
  }
}

export { ObservedProduct, Fees, Profit };
Enter fullscreen mode Exit fullscreen mode

A complete example is here ๐Ÿ‘‰ https://stackblitz.com/edit/vitejs-vite-kyucyd?file=main.js

Conclusion

Use this pattern when changes to the state of one object may require changing other objects, and the actual set of objects is unknown beforehand or changes dynamically.


I hope you found it helpful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Communityโ€”every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple โ€œthank youโ€ goes a long wayโ€”express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay