node03-events
目录:
node01-创建服务器
node02-util
node03-events
node04-buffer
node05-fs
node06-path
node07-http
node08-express
node09-cookie
events模块:
1 // var events = require("events").EventEmitter();//老式写法 2 var events = require("events"); 3 var util = require("util"); 4 function Goddess(){ 5 //女神类,会触发一些事件,比如饿了 6 } 7 function Boy(name,response){ 8 this.name = name; 9 this.response = response; 10 } 11 util.inherits(Goddess,events);//继承事件的各种方法和属性 12 13 var girl = new Goddess(); 14 var boy1 = new Boy("备胎1",function(){ 15 console.log("吃鸡腿"); 16 }); 17 var boy2 = new Boy("备胎2",function(){ 18 console.log("吃牛排"); 19 }); 20 21 22 girl.setMaxListeners(3);//设置最大事件数 23 //添加事件 24 girl.on("ele",boy1.response); 25 girl.addListener("ele",function(){ 26 console.log("自己做点吃的"); 27 }); 28 girl.on("ele",boy2.response); 29 girl.once("die",function(){ 30 console.log("死了"); 31 }); 32 // girl.removeListener("ele",boy1.response);//移除事件 33 girl.removeAllListeners("ele");//移除ele 34 //发射事件 35 girl.emit("ele"); 36 girl.emit("die"); 37 girl.emit("ele"); 38 girl.emit("die");