Skip to content

Commit dcbf40a

Browse files
committed
node事件模块初探
1 parent 24dcbbe commit dcbf40a

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

‎Node/eventemitter/index.js‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"use strict"
2+
3+
let util=require("util");
4+
let EventEmitter=require("events").EventEmitter;
5+
6+
7+
8+
function MusicPlayer(){
9+
this.play=false;
10+
EventEmitter.call(this);
11+
}
12+
13+
//类的继承
14+
MusicPlayer.prototype=Object.create(EventEmitter.prototype);
15+
16+
let AudioDevice={
17+
play:function(){
18+
console.log("Music is playing...");
19+
},
20+
stop:function(){
21+
console.log("Music is Stop!");
22+
}
23+
}
24+
25+
var music=new MusicPlayer();
26+
27+
//通过on注册事件 ,可以添加多个监听器
28+
music.on("play",function(){
29+
this.play=true;
30+
AudioDevice.play();
31+
});
32+
33+
music.on("play",function(){
34+
console.log("新添加一个监听器");
35+
})
36+
37+
music.on("stop",function(){
38+
this.play=false;
39+
AudioDevice.stop();
40+
})
41+
42+
music.removeE
43+
44+
//通过emit触发事件
45+
music.emit("play"); vf
46+
47+
48+
setTimeout(function(){
49+
music.emit("stop");
50+
},2000);
51+
52+
53+
54+
55+
56+
57+
58+
59+

0 commit comments

Comments
 (0)