Chinaunix首页 | 论坛 | 博客
  • 博客访问: 313003
  • 博文数量: 103
  • 博客积分: 1590
  • 博客等级: 上尉
  • 技术积分: 1075
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-02 10:17
文章分类

全部博文(103)

文章存档

2013年(32)

2012年(7)

2010年(64)

我的朋友

分类: Web开发

2013-06-02 12:31:11

events

参考:


 Many objects in Node emit events: a net.Server emits an event each time a peer connects to it, a fs.readStream emits an event when the file is opened. All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");

Node引擎中很多对象都会触发事件:例如net.Server会在每一次有客户端连接到它时触发事件,又如fs.readStream会在文件打开时触发事件。所有能够触发事件的对象都是events.EventEmitter的实例。你可以通过require("events");访问这个模块。

Functions can then be attached to objects, to be executed when an event is emitted. These functions are called listeners.

可以将函数注册给对象,使其在事件触发时执行,此类函数被称作监听器

When an EventEmitter instance experiences an error, the typical action is to emit an 'error' event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.

当EventEmitter事件触发器遇到错误时,典型的处理方式是它将触发一个'error'事件。Error事件的特殊性在于:如果没有函数处理这个事件,它将会输出调用堆栈,并随之退出应用程序。

All EventEmitters emit the event 'newListener' when new listeners are added.

当新的事件监听器被添加时,所有的事件触发器都将触发名为'newListener'的事件。

emitter.once(event, listener)

Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed.
 为事件添加一次性的监听器。该监听器在事件第一次触发时执行,过后将被移除。

emitter.listeners(event)

Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.

返回指定事件的监听器数组对象,你可以对该数组进行操作,比如说删除监听器等。

emitter.emit(event, [arg1], [arg2], [...])

Execute each of the listeners in order with the supplied arguments.
 以提供的参数作为监听器函数的参数,顺序执行监听器列表中的每个监听器函数。

 
示例:

 
结果:

listener1 byvoid 1991

listener2 byvoid 1991

Ah, we have our first user!

someone connected xx!

someone connected xx!

[ { [Function]


阅读(657) | 评论(0) | 转发(0) |
0

上一篇:Node.js util模块

下一篇:nodejs file 模块

给主人留下些什么吧!~~