【发布时间】:2018-01-27 05:48:45
【问题描述】:
我是 es6 和 eventEmitter 的新手。我已经准备了一个节点事件基础样式的模块,现在我正在尝试转换为 es6 calass 样式。在这里
// eventStyle.js
const events = require('events');
const util = require('util');
var Customer = function() {
// console.log(typeof this);
events.EventEmitter.call(this);
// this is only public function
this.register = function(email, password) {
var newCustomer = {email:email, password:password}
this.emit("newRegistation", newCustomer)
}
var _validate = function(customer) {
if(customer.password=='password')
this.emit("validated", customer)
else
this.emit("registationFailed", customer)
}
var _insert = function(customer) {
this.emit("added", customer)
}
var _sendEmail = function(customer) {
this.emit("emailSent", customer)
}
var _registationSuccessful = function(customer) {
this.emit("registationSuccessful", customer)
}
this.on("newRegistation", _validate)
this.on("validated", _insert)
this.on("added", _sendEmail)
this.on("emailSent", _registationSuccessful)
}
util.inherits(Customer, events.EventEmitter )
module.exports = 客户
//eventApp.js
const Customer = require('./eventStyle');
customer = new Customer();
// console.log(customer);
customer.on("registationSuccessful", ()=>{
console.log("well done");
})
customer.on("registationFailed", ()=>{
console.log("sorry error");
})
console.log(typeof customer.register);
setTimeout(()=>customer.register(), 1000);
//现在我的 eventStyle.js
的基于 es6 的代码(不适用于我)const events = require('events');
const util = require('util');
class Customer {
constuctor(){
console.log("cons",this);
events.EventEmitter.call(this);
this.on("newRegistation", _validate)
this.on("validated", _insert)
this.on("added", _sendEmail)
this.on("emailSent", _registationSuccessful)
}
// this is only public function
register(email, password) {
var newCustomer = {email:email, password:password}
console.log(this);
this.emit("newRegistation", newCustomer)
}
_validate(customer) {
if(customer.password=='password')
this.emit("validated", customer)
else
this.emit("registationFailed", customer)
}
_insert(customer) {
this.emit("added", customer)
}
_sendEmail(customer) {
this.emit("emailSent", customer)
}
_registationSuccessful(customer) {
this.emit("registationSuccessful", customer)
}
}
util.inherits(Customer, events.EventEmitter )
module.exports = Customer
有人告诉我我弄错了什么。提前致谢
【问题讨论】:
-
你的问题是什么?
-
也许 Babel 是你需要的。
-
@Sunday:正好相反。
-
永远不要更改正在运行的系统...为什么需要课程?没有它就不能正常工作吗?
-
“现在我的基于 es6 的代码(不适合我)” 不工作如何?你有什么问题?发生什么了?你期望会发生什么?您看到了什么错误?
标签: javascript node.js events ecmascript-6 eventemitter