Home > Web Front-end > JS Tutorial > JavaScript Design Patterns - Behavioral - Observer

JavaScript Design Patterns - Behavioral - Observer

王林
Release: 2024-08-12 18:41:06
Original
950 people have browsed it

JavaScript Design Patterns - Behavioral - Observer

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 };
Copy after login

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:

  • Medium: https://medium.com/@nhannguyendevjs/
  • Dev: https://dev.to/nhannguyendevjs/
  • Hashnode: https://nhannguyen.hashnode.dev/
  • Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
  • X (formerly Twitter): https://twitter.com/nhannguyendevjs/
  • Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs

The above is the detailed content of JavaScript Design Patterns - Behavioral - Observer. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template