在 ES6 中使用 EventEmitter class
Use EventEmitter in ES6 class
我正在尝试在我自己的 class 运行 ES6 中获取 EventEmitter:
"use strict";
const EventEmitter = require('events');
class Client extends EventEmitter{
constructor(token, client_id, client_secret, redirect_uri, code){
super();
this.token = token;
this.client_id = client_id;
this.client_secret = client_secret;
this.redirect_uri = redirect_uri;
this.code = code;
}
eventTest(){
this.emit("event");
console.log(this.token);
}
}
let testClient = new Client(1,2,3,4,5);
testClient.eventTest();
testClient.on('event', () => {console.log('triggerd!')} );
但是活动什么也没做^^
在没有 ES6 的情况下,我可以使用以下代码:
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Client = function(credentials) {
var self = this;
function eventTest() {
self.emit('event');
}
};
util.inherits(Client, EventEmitter);
有人知道如何在 ES6 中正确地做到这一点吗?
事件是同步的——你在听之前触发它。使用
const testClient = new Client(1,2,3,4,5);
testClient.on('event', () => {console.log('triggered!')} );
testClient.eventTest();
您可以使用 process.nextTick()
让您的代码异步。之后一切都会按预期工作。这是节点文档中的注释:
The process.nextTick()
method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.
eventTest(){
process.nextTick(() => {
this.emit("event");
});
console.log(this.token);
}
我正在尝试在我自己的 class 运行 ES6 中获取 EventEmitter:
"use strict";
const EventEmitter = require('events');
class Client extends EventEmitter{
constructor(token, client_id, client_secret, redirect_uri, code){
super();
this.token = token;
this.client_id = client_id;
this.client_secret = client_secret;
this.redirect_uri = redirect_uri;
this.code = code;
}
eventTest(){
this.emit("event");
console.log(this.token);
}
}
let testClient = new Client(1,2,3,4,5);
testClient.eventTest();
testClient.on('event', () => {console.log('triggerd!')} );
但是活动什么也没做^^
在没有 ES6 的情况下,我可以使用以下代码:
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Client = function(credentials) {
var self = this;
function eventTest() {
self.emit('event');
}
};
util.inherits(Client, EventEmitter);
有人知道如何在 ES6 中正确地做到这一点吗?
事件是同步的——你在听之前触发它。使用
const testClient = new Client(1,2,3,4,5);
testClient.on('event', () => {console.log('triggered!')} );
testClient.eventTest();
您可以使用 process.nextTick()
让您的代码异步。之后一切都会按预期工作。这是节点文档中的注释:
The
process.nextTick()
method adds the callback to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.
eventTest(){
process.nextTick(() => {
this.emit("event");
});
console.log(this.token);
}