SHARE
TWEET

Untitled

a guest Apr 25th, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Subject {
  2.     constructor() {
  3.         this.observers = []
  4.     }
  5.     subscribe(observer) {
  6.         this.observers.push(observer)
  7.     }
  8.     unsubscribe(observer) {
  9.         if (!observer) return
  10.  
  11.         this.observers = this.observers.filter(el => !this.observers.includes(el))
  12.     }
  13.     notify(data) {
  14.         if (this.observers.length > 0) {
  15.             this.observers.forEach(el => el.update(data))
  16.         }
  17.     }
  18. }
  19.  
  20. class Observer {
  21.     update() {}
  22. }
  23.  
  24. class Client extends Observer {
  25.     update(data) {
  26.         this.doSomethingWithIt(data)
  27.     }
  28.     doSomethingWithIt(data) {
  29.         console.log(data, 'This is from client 1')
  30.     }
  31. }
  32.  
  33.  
  34. class Client2 extends Observer {
  35.     update(data) {
  36.         this.domeSomethingTotalyDifferent(data)
  37.     }
  38.     domeSomethingTotalyDifferent(data) {
  39.         console.log(data, 'This is from client 2')
  40.     }
  41. }
  42.  
  43.  
  44. class State extends Subject {
  45.     constructor() {
  46.         super()
  47.         this._state = {}
  48.     }
  49.     setState(data) {
  50.         this._state = Object.assign(this._state, data)
  51.         this.notify(this._state)
  52.     }
  53.  
  54.     get state() {
  55.         return this._state
  56.     }
  57. }
  58.  
  59.  
  60. const dummyState = { name: 'John Doe' }
  61. const dummyState2 = { name: 'Jane Doe' }
  62.  
  63. const client = new Client()
  64. const client2 = new Client2()
  65. const state = new State()
  66.  
  67. state.setState(dummyState)
  68. state.subscribe(client)
  69. state.setState(dummyState)
  70. state.unsubscribe(client)
  71. state.subscribe(client2)
  72. state.setState(dummyState)
  73. state.setState(dummyState2)
  74. state.setState(dummyState)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top