我试图让这个模块在Node 8.7上运行 当我运行它时,控制台抛出类型错误回调不是一个函数(在emit方法上)。
我正在将这个模块与一个类一起使用,以使另一个类继承自Event Emitter。
当我在一个文件上尝试相同的代码(使用Event Emitter,另一个类作为单独的类)时,Node会不断地抛出随机错误。
//export class EventEmitter...
class EventEmitter{
constructor(){
this.events = {};
}
on(eventName,callback){
if (typeof this.events[eventName] !== 'object') {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
emit(eventName, ...rest) {
if (this.events[eventName]) {
this.events[eventName].forEach((callback) => {
callback(rest);
});
} else {
console.log("The event doesn't exists.");
}
}
off(eventName,callback){
var index;
if (typeof this.events[eventName] === 'object') {
index = this.events[eventName].indexOf(callback);
if (index > -1) {
this.events[eventName].splice(index, 1);
}
}
}
}
module.exports = EventEmitter;
按要求添加了movie.js类和对象
//import {EventEmitter} from "./eventEmitter.js"
var EventEmitter = require("./eventEmitter.js");
class Movie extends EventEmitter {
constructor(name,year,duration){
super();//invokes father class constructor
this.title = name;
this.year = year;
this.duration = duration;
this.startPlay = 0;
this.currentMovieTime = 0;//aca iba var date
}
play(){
var date = new Date();//agregada nueva
this.startPlay = date.getMinutes();
}
pause(){
var date = new Date(); //agregada nueva
let time2 = date.getMinutes();
this.currentMovieTime+= (time2 - this.startPlay);
this.startPlay = time2;
if(this.currentMovieTime > this.duration)
this.currentMovieTime = this.duration;
}
resume(){
this.startPlay =0;
this.currentMovieTime=0;
}
}
let film = new Movie("Harry Potter",2001,120);
let playFunc = film.play();
film.on('play',playFunc);
let resumeFunc = film.resume();
film.on('resume',resumeFunc);
let pauseFunc = film.pause();
film.on('pause',pauseFunc);
film.emit('play');
film.emit('pause');
film.emit('resume');