JavaScript Design Patterns - Behavioral - Observer

王林
發布: 2024-08-12 18:41:06
原創
817 人瀏覽過

JavaScript Design Patterns - Behavioral - Observer

Theobserverpattern 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 theregister()method. When something is updated, thenotifyAll()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 };
登入後複製

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

以上是JavaScript Design Patterns - Behavioral - Observer的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!