Last active
February 22, 2017 21:20
-
-
Save mallond/78986f7db045fa10fac2412e7a75a8e5 to your computer and use it in GitHub Desktop.
Node Emitter Example
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
/** | |
* Created by dm on 2/22/17. | |
*/ | |
'use strict'; | |
// Set Up a Node Global OnOff Emitter | |
const events = require('events'); | |
if (!global.OnOffEmitter) { | |
global.OnOffEmitter = new events.EventEmitter(); | |
} | |
// OnOff Class name=device name, emitter is the emitter | |
class OnOff { | |
constructor(name, emitter) { | |
this.name = name; | |
this.state = 'off'; | |
this.emitter = emitter; | |
} | |
on() { | |
this.state = 'on'; | |
this.emitter.emit('on', this.name+' '+this.state); | |
return this.state; | |
} | |
off() { | |
this.state = 'off'; | |
this.emitter.emit('off', this.name+' '+this.state); | |
return this.state; | |
} | |
} | |
// Construct Two Devices | |
const onOffLight = new OnOff('light', global.OnOffEmitter); | |
const onOffCar = new OnOff('car', global.OnOffEmitter); | |
// Listen when On | |
global.OnOffEmitter.on('on', (state)=>{ | |
console.log(state); | |
}); | |
// Listen when Off | |
global.OnOffEmitter.on('off', (state)=>{ | |
console.log(state); | |
}); | |
global.OnOffEmitter.on('error', (err) => { | |
console.log('whoops! there was an error', err); | |
}); | |
// Run a few Tests | |
onOffLight.on(); | |
onOffLight.off(); | |
onOffLight.on(); | |
onOffLight.off(); | |
onOffLight.on(); | |
onOffLight.off(); | |
onOffLight.on(); | |
onOffLight.off(); | |
onOffCar.on(); | |
onOffCar.off(); | |
onOffCar.on(); | |
onOffCar.off(); | |
onOffCar.on(); | |
onOffCar.off(); | |
onOffCar.on(); | |
onOffCar.off(); | |
global.OnOffEmitter.emit('error', new Error('Whoops!')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment