node.js EventEmitter发送和接收事件
EventEmitter是nodejs核心的一部分。很多nodejs对象继承自EventEmitter,用来处理事件,及回调。api文档地址:
http://nodejs.org/api/events.html#events_class_events_eventemitter
Event:
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 ofevents.EventEmitter. You can access this module by doing: require("events");
Typically, event names are represented by a camel-cased string, however, there aren't any strict restrictions on that, as any string will be accepted.
Functions can then be attached to objects, to be executed when an event is emitted. These functions are calledlisteners. Inside a listener function, this refers to the EventEmitter that the listener was attached to.
Class: events.EventEmitter#
To access the EventEmitter class, require('events').EventEmitter.
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.
All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.
emitter.addListener(event, listener)#
emitter.on(event, listener)#
Adds a listener to the end of the listeners array for the specified event.
server.on('connection', function (stream) {
console.log('someone connected!');
});
Returns emitter, so calls can be chained.
emitter.once(event, listener)#
Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});
Returns emitter, so calls can be chained.
emitter.removeListener(event, listener)#
Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Returns emitter, so calls can be chained.
emitter.removeAllListeners([event])#
Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's on an emitter that you didn't create (e.g. sockets or file streams).
Returns emitter, so calls can be chained.
emitter.setMaxListeners(n)#
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.
emitter.listeners(event)#
Returns an array of listeners for the specified event.
server.on('connection', function (stream) {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
emitter.emit(event, [arg1], [arg2], [...])#
Execute each of the listeners in order with the supplied arguments.
Returns true if event had listeners, false otherwise.
Class Method: EventEmitter.listenerCount(emitter, event)#
Return the number of listeners for a given event.
Event: 'newListener'#
eventString The event namelistenerFunction The event handler function
This event is emitted any time someone adds a new listener. It is unspecified if listener is in the list returned by emitter.listeners(event).
Event: 'removeListener'#
eventString The event namelistenerFunction The event handler function
This event is emitted any time someone removes a listener. It is unspecified if listener is in the list returned byemitter.listeners(event).
/*
EventEmitter发送和接收事件
HTTPServer和HTTPClient类,它们都继承自EventEmitter EventEmitter被定义在Node的事件(events)模块中,直接使用EventEmitter类需要先声明require('events'),
否则不必显式声明require('events'),因为Node中很多对象都无需你调用require('events')就会使用EventEmitter
*/
var events = require('events');
var util = require('util'); function Pulser(){
events.EventEmitter.call(this);
}
util.inherits(Pulser, events.EventEmitter); Pulser.prototype.start = function(){
var self = this;
this.id = setInterval(function(){
util.log('>>>>pulse');
self.emit('pulse');
util.log('<<<<pulse');
}, 1000);
}
//定义了一个类Pulser,该类(通过util.inherits)继承自EventEmitter,它的作用是每隔一秒钟向所有监听器发送一个定时事件。
//start方法使用了setInterval这个函数来定期重复执行回调函数,并调用emit方法将pulse事件发送给每一个监听器 //使用Pulser对象
/*
创建了一个Pulser对象并处理其pulse事件,执行pulser.on('pulse'..)为pulse事件和回调函数建立联系
*/
var pulser = new Pulser();
pulser.on('pulse', function(){
util.log('pulse received');
});
pulser.start(); //对象使用emit函数发送事件,所有注册到对应事件的监听器都可以收到事件;
//通过调用.on方法注册监听器,参数是事件名,并用一个回调函数接收事件
//通常来说,有一些数据需要伴随着事件同时发送 self.emit('eventName', data1, data2, ..);
//emitter.on('eventName', function(data1, data2,..){
//接收到事件后的操作
// });
node.js EventEmitter发送和接收事件的更多相关文章
- 从零开始学习Node.js例子六 EventEmitter发送和接收事件
pulser.js /* EventEmitter发送和接收事件 HTTPServer和HTTPClient类,它们都继承自EventEmitter EventEmitter被定义在Node的事件(e ...
- 20.Node.js EventEmitter的方法和事件
转自:http://www.runoob.com/nodejs/nodejs-tutorial.html EventEmitter 提供了多个属性,如 on 和 emit.on 函数用于绑定事件函数, ...
- Node.js EventEmitter
Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列. Node.js里面的许多对象都会分发事件:一个net.Server对象会在每次有 ...
- 7、Node.js EventEmitter
#######################################################################################介绍Node.js Eve ...
- 转:Node.js邮件发送组件- Nodemailer 1.0发布
原文来自于http://www.infoq.com/cn/news/2014/07/node.js-nodemailer1.0-publish Nodemailer是一个简单易用的Node.js邮件发 ...
- 解决Postman发送post数据但是Node.js中req.body接收不到数据的问题[已解决]
之前编写后台接口,测试数据都是使用的Postman,相当的方便,之前也一直使用get方法,编写Node.js一直没有问题,但是由于要编写一个注册/登陆的功能,所以发送的post数据,后台的逻辑已经编写 ...
- Node.js EventEmitter(事件队列)
Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列. Node.js里面的许多对象都会分发事件:一个net.Server对象会在每次有新连接时分发一个事件, 一个fs.read ...
- Node.js 学习(六)Node.js EventEmitter
Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列. Node.js里面的许多对象都会分发事件:一个net.Server对象会在每次有新连接时分发一个事件, 一个fs.read ...
- 19.Node.js EventEmitter
转自:http://www.runoob.com/nodejs/nodejs-tutorial.html Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列. Node.js里 ...
随机推荐
- JBoss部署项目log4j配置会造成死锁问题,浏览器访问一直pending状态
今天将项目部署到JBoss服务器上,部署成功后,浏览器访问页面一直在等待响应. 查了很长时间,最后在服务器上通过jstack pid命令查看Java堆栈信息,发现了有两个线程死锁. 看到造成死锁的原因 ...
- spring 计划任务:cron表达式
Cron表达式是一个字符串,字符串以5或6个空格隔开,分开工6或7个域,每一个域代表一个含义,Cron有如下两种语法 格式: Seconds Minutes Hours DayofMonth Mont ...
- 5步解决移动设备上的300ms点击延迟
译者:jmouse 大多数基于触摸的浏览器设备,在点击时都会有个 300ms 的事件触发等待时间,做过 web app 开发的同学应该都遇到过这个情况,通过下面的5步可以轻松搞定这个延迟. 1.不要太 ...
- Export功能 导致 页面显示很多非法字符,还可能页面显示两次
private void exportBinaryToExcel(byte[] bytes, string filename) { Response.AddHeader("Content-D ...
- amcharts 网页绘图插件
Amcharts是一组js图表,你可以免费使用在你的网站和基于网络的产品(非开源). Amcharts可以从简单的json提取数据,也可以从动态数据读取生成,比如PHP, .NET, Ruby on ...
- 当前标识(NT AUTHORITY\NETWORK SERVICE)没有对“C:\WINDOWS2\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files”的写访问权限。
卸载了域控制器之后,IIS出现“当前标识(NT AUTHORITY\NETWORK SERVICE)没有对“C:\WINDOWS2\Microsoft.NET\Framework\v4.0.30319 ...
- 《C和指针》 读书笔记 -- 第7章 函数
1.当程序调用一个无法见到原型的函数时,编译器便认为该函数返回一个整型值.如果这个值实际上是非整型值时,还得执行类型转换,所以函数原型声明有时很重要. 2.值的类型并不是值的内在本质,而是取决于它被使 ...
- C语言获取网页源代码的学习所得
研究了一天这个玩意感觉挺有意思的. 刚开始是什么都不懂,现在写出来一段代码感觉略微有点意思了. 下面我分享一下学习过程和自己的理解. 整体过程大概就是如下情况: 先搜了一下别人的写这个东西的代码. 研 ...
- (转)Qt Model/View 学习笔记 (二)——Qt Model/View模式举例
Qt Model/View模式举例 Qt提供了两个标准的models:QStandardItemModel和QDirModel.QStandardItemModel是一个多用途的model,可用于表示 ...
- javaweb 在netbeans 上的部署问题
最近用netbeans去部署开发 javaweb程序!现总结一下自己的安装开发过程. 第一,在官网上下载netbeans时,有自带的tomcat,可以直接使用这个服务器,在我这儿这个自带的tomcat ...