Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created December 11, 2017 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/f78da02c21825fa8c24b98d8444d7614 to your computer and use it in GitHub Desktop.
Save kobus1998/f78da02c21825fa8c24b98d8444d7614 to your computer and use it in GitHub Desktop.
Javascript observing
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
/**
* 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)
})
}
}
/**
* 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