Created
December 11, 2017 10:23
-
-
Save kobus1998/f78da02c21825fa8c24b98d8444d7614 to your computer and use it in GitHub Desktop.
Javascript observing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const observer = new Observer() | |
let u1 = new User({name: 'jan'}, observer) | |
let u2 = new User({name: 'piet'}, observer) | |
let u3 = new User({name: 'klaas'}, observer) | |
let u4 = new User({name: 'kees'}, observer) | |
u2.sendMessage('Hi everybody!') | |
// output: | |
// "jan got a message from piet: Hi everybody!" | |
// "piet sent a message: Hi everybody!" | |
// "klaas got a message from piet: Hi everybody!" | |
// "kees got a message from piet: Hi everybody!" | |
// https://codepen.io/kobuxz/pen/VrJaJj |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* All observables get collected here. | |
* notify executes the function in the type | |
* variable for all attached objects. | |
*/ | |
class Observer { | |
constructor () { | |
this.observables = [] | |
} | |
attach (obj) { | |
this.observables.push(obj) | |
} | |
notify (type, obj, user) { | |
this.observables.forEach((val, key, arr) => { | |
val[type](obj, user) | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* In the constructor the class gets attached | |
* to the observer class. | |
* When sendMessage gets executed | |
* all classes attached to the same | |
* observer gets notified. | |
*/ | |
class User { | |
constructor (obj, observer) { | |
this.data = obj | |
this.observer = observer | |
this.observer.attach(this) | |
} | |
notify () { | |
this.observer.notify(this) | |
} | |
getMessage (msg, user) { | |
if (this.data.name !== user.data.name) { | |
console.log(`${this.data.name} got a message from ${user.data.name}: ${msg}`) | |
} else { | |
console.log(`${this.data.name} sent a message: ${msg}`) | |
} | |
} | |
sendMessage (msg) { | |
this.observer.notify('getMessage', msg, this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment