Skip to content

Instantly share code, notes, and snippets.

@ihollander
Created November 27, 2018 18:11
Show Gist options
  • Save ihollander/e9a3bec0614d2be90129c99ecbb44ed7 to your computer and use it in GitHub Desktop.
Save ihollander/e9a3bec0614d2be90129c99ecbb44ed7 to your computer and use it in GitHub Desktop.
Observer Pattern pt2
class FluxModel extends EventEmitter {
constructor() {
super() // initialize the EventEmitter
this.time = new Date() // set the current time
this.isNighttime = this.getNighttime() // check if it is nighttime
setInterval(this.updateTime.bind(this), 60000) // update our model's state every minute
}
updateTime() {
let previousIsNighttimeState = this.isNighttime // save the PREVIOUS STATE of our application
this.time = new Date() // set the CURRENT STATE of our application
this.isNighttime = this.getNighttime()
// trigger event on a STATE change (going from day to night)
if (previousIsNighttimeState && !this.isNighttime) { // from night to day
this.dispatchEvent('daytime', this.time)
} else if (!previousIsNighttimeState && this.isNighttime) { // from day to night
this.dispatchEvent('nighttime', this.time)
}
}
getNighttime() {
return this.time.getHours() > 18 && this.time.getHours() < 6
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment