node. JS is event-driven, and some of our custom JS objects need to be able to listen for events and launch events. In node. js, the event is emitted using a Eventemitter object in the events module. It should be used to implement the observer design pattern to add the event listener to the object and remove, before writing the OC block, there are also some observer design patterns, often used in OC: Notification Center, KVO, is also easy to understand.
. AddListener (Eventname,callback): Attaches a callback function to the listener of the object. When the EventName event is triggered, the callback function is placed in the event queue for execution.
. On (eventname,callback): Same as. AddListener.
. Once (Eventname,callback), which is also monitored only for the first time is triggered.
. Listeners (EventName): Returns an array of listener functions connected to the EventName event.
. Setmaxlisteners (N): If more than n listeners are added to the Eventrmitter object, an alert will be set.
. RemoveListener (Eventname,callback): Removes the callback function from the EventName event of the Eventemitter object.
Second, the above is written so much is also the use of Eventemitter object methods, custom objects how to use them is the key!
The listening methods are all Eventemitter objects, and if you want the custom object to use these methods, you need to inherit the eventemitter.
There are several ways to implement inheritance in JS: constructors, prototype chains, call, apply, etc., you can Baidu: JS inheritance.
Simply add the Events.EventEmitter.prototype to the object prototype. (in Eventemitter, the listener method is added via prototype)
Third, use
var events = require (' events '); function account () {this.balance = 0; Buy the information book to add the following statement, I will comment out the following statement can also implement inheritance, it should be unnecessary bar//events. Eventemitter.call (this); This.deposit = function (amount) {this.balance + = amount; This.emit (' balancechanged '); }; This.withdraw = function (amount) {this.balance-= amount; This.emit (' balancechanged '); };} account.prototype.__proto__ = events. Eventemitter.prototype;function displaybalance () {Console.log ("account balance: $%d", this.balance);} function Checkoverdraw () {if (This.balance < 0) {Console.log ("account overdrawn!!!"); }}function Checkgoal (ACC, goal) {if (Acc.balance > goal) {Console.log ("goal achieved!!!"); }}var account = new account (), Account.on ("balancechanged", Displaybalance), Account.on ("balancechanged", Checkoverdraw); Account.on ("Balancechanged", function () {checkgoal (this, 1000);}); Account.deposit (account.deposit); Account.deposit (+); Account.withdraw (1200);
Account balance: $220 accountBalance: $540 AccountBalance: $1140Goal achieved!!! Account Balance: $-60 accountoverdrawn!!! with exit code 0
node. JS custom Object Event Listener and launch