9. Event-Driven Programming and Built-In Modules
Activity 13: Building an Event-Driven Module
Solution:
Perform the following steps to complete this activity:
- Import the
events
module:const EventEmitter = require('events');
- Create the
SmokeDetector
class that extendsEventEmitter
and setbatteryLevel
to10
:class SmokeDetector extends EventEmitter { Â Â Â Â constructor() { Â Â Â Â Â Â Â Â super(); Â Â Â Â Â Â Â Â this.batteryLevel = 10; Â Â Â Â } }
In our constructor, because we are extending the
EventEmitter
class and we are assigning a custom property,batteryLevel
, we will need to callsuper
inside the constructor and setbatteryLevel
to10
. - Create a
test
method inside theSmokeDetector
class that will test the battery level and emit alow battery
message in the event that the battery is low:test() { Â Â Â Â Â Â Â Â if (this...