关于EventEmitter的用法

1 var EventEmitter = require("events").EventEmitter;
2 var ee = new EventEmitter();
3 ee.on("someEvent", function () {
4     console.log("event has occured");
5 });
6  
7 ee.emit("someEvent");

emit方法可以触发多个同样的事件,比如我们的页面中绑定了多个同样的someEven事件。

ee.on("someEvent", function () { console.log("event 1"); });
ee.on("someEvent", function () { console.log("event 2"); });
ee.on("someEvent", function () { console.log("event 3"); });
ee.on("someEvent", function () { console.log("event 4"); });
ee.on("someEvent", function () { console.log("event 5"); });
ee.on("someEvent", function () { console.log("event 6"); });
ee.on("someEvent", function () { console.log("event 7"); });
ee.on("someEvent", function () { console.log("event 8"); });
ee.on("someEvent", function () { console.log("event 9"); });
ee.on("someEvent", function () { console.log("event 10"); });
ee.on("someEvent", function () { console.log("event 11"); });
 
ee.emit("someEvent");

上面绑定的11个someEvent事件都会触发,但是控制台会有一条警告,因为事件对象默认监听的事件数量是10个,我们可以通过代码设置改变这个数值,例如:

1 ee.setMaxListeners(20);

事件对象还有其他方法:

1,once()监听一次

2,removeListener , removeAllListeners() 移除监听事件/移除所有监听的事件

比如在UserList.js文件中有UserList类

 1 var util         = require("util");
 2 var EventEmitter = require("events").EventEmitter;
 3 
 4 var id = 1;
 5 var database = {
 6     users: [
 7         { id: id++, name: "Joe Smith",  occupation: "developer"    },
 8         { id: id++, name: "Jane Doe",   occupation: "data analyst" },
 9         { id: id++, name: "John Henry", occupation: "designer"     }
10     ]
11 };
12 
13 util.inherits(UserList, EventEmitter);
14 /*或者这样
15 function UserList () {
16     EventEmitter.call(this);
17 }*/
18 
19 UserList.prototype.save = function (obj) {
20     obj.id = id++;
21     database.users.push(obj);
22     this.emit("saved-user", obj);  
23 };
24 
25 UserList.prototype.all = function () {
26     return database.users;
27 };
28  
29 module.exports = UserList

 

现在我们可以在另外一个文件中这样写:

1 var UserList = require("./userlist");
2 var users = new UserList();
3  
4 users.on("saved-user", function (user) {
5     console.log("saved: " + user.name + " (" + user.id + ")");
6 });
7  
8 users.save({ name: "Jane Doe", occupation: "manager" });
9 users.save({ name: "John Jacob", occupation: "developer" });
1 //输出结果
2 saved: Jane Doe (4)
3 saved: John Jacob (5)

 

posted @ 2016-12-26 17:40  向着太阳生  阅读(8998)  评论(0编辑  收藏  举报