event模块是nodejs系统中十分重要的一个模块,使用该模块我们可以实现事件的绑定的触发,为什么我们需要这个模块呢,因为nodejs是单线程异步的。

一、什么是单线程异步:

我们可以从JavaScript来理解,就是存在一个等待执行队列,每当有代码行为产生,我们便将其随机放到等待执行队列,但是由于单线程的原因,我们一次只能处理一个任务,只有在当线程空闲时才能处理下一个任务,在线程处理时,我们仍然可以将要处理的任务放到等待执行队列中,也就说线程的任务处理和我们读取代码放任务到等待执行队列上这两个行为是可以同时进行的,即异步,线程一次只能处理一个任务,即单线程。

如下例子:

setTimeout(function (){
console.log('I am coming');
}, 100); console.log('before while');

结果是先打印before while,然后再打印I am coming,而不是在100ms的延时时阻塞之后代码的执行,注册定时器后继续执行之后的代码。

二、event模块的主要方法:

  • on:添加事件(事件队列尾部添加)
  • once:添加只能触发一次便失效的事件(事件队列尾部添加)
  • prependListener:添加事件(添加到事件队列头部)
  • prependOnceListener:添加只能触发一次便失效的事件(添加到事件队列头部)
  • emit:触发事件
  • removeListener:删除某个事件
  1. on(eventName, listener[, arg1][, arg2]...)

eventName:注册事件名字

listener:事件处理函数

arg1,arg2:往事件处理函数中传入的参数

"use srict";

const Event = require('events');

const event1 = new Event();

event1.on('come', function () {
console.log('I am coming');
}); event1.emit('come'); // I am coming

  2. once 同on,但是只能触发一次,触发一次后便从事件队列中删除

  3. prependListener 同on,但是是往事件队列头部添加

  4. prependOnceListener 同on,但是是往事件队列头部添加,且只能触发一次

  5. emit(eventName)触发eventName事件

  6. removeListener(eventName)解除eventName事件绑定

同一事件可以绑定多次,触发时按照事件队列顺序执行,on和once是往事件队列尾部添加,prependListener和prependOnceListener是往事件队列头部添加,这便形成了同一事件的执行顺序

"use srict";

const Event = require('events');

const event1 = new Event();

event1.on('come', function () {
console.log('I am coming01');
});
event1.on('come', function () {
console.log('I am coming02');
});
event1.prependListener('come', function () {
console.log('I am coming03');
})
event1.emit('come');
/*
I am coming03
I am coming01
I am coming02
*/

event方法简单模拟实现:

"use strict";

// evnet  实现模拟
EventEmitter.prototype = {
// on方法
on: function(eventName, cb) {
this.events[eventName] = cb;
},
// emit,传参
emit: function(eventName) { const args = Array.prototype.slice.call(arguments, 1);
const cb = this.events[eventName];
cb.apply(this, args);
console.log(this);
}, }
function EventEmitter() {
this.events = {};
} const event1 = new EventEmitter(); event1.on('call', (name, word) => {
console.log('I am calling,', name, word);
});
event1.emit('call', 'john', 'hello'); // I am calling

三、event模块的继承:

event模块可以被其他类继承,从而具有event模块的属性

两种方法:

1、util.inherits

"use srict";

const Event = require('events');
const util = require('util'); // Phone类
Phone.prototype.message = function () {
console.log('I am sending message');
}
function Phone() {}
// 通过util.inherits继承
util.inherits(Phone, Event);
// 测试
const phone = new Phone();
phone.on('call', function () {
this.message();
});
phone.emit('call'); // I am sending message

2、通过ES6的extends实现继承(推荐)

"use srict";

const Event = require('events');
// extends
class Phone extends Event {
message() {
console.log('I am sending message');
}
}
// 测试
const phone = new Phone();
phone.on('call', function () {
this.message();
});
phone.emit('call'); // I am sending message

----------------------------------------------------------------------------------end

nodejs模块之event的更多相关文章

  1. [NodeJs系列][译]理解NodeJs中的Event Loop、Timers以及process.nextTick()

    译者注: 为什么要翻译?其实在翻译这篇文章前,笔者有Google了一下中文翻译,看的不是很明白,所以才有自己翻译的打算,当然能力有限,文中或有错漏,欢迎指正. 文末会有几个小问题,大家不妨一起思考一下 ...

  2. nodejs nodejs模块使用及简单的示例

    nodejs模块使用及简单的示例 参考菜鸟教程网:http://www.runoob.com/ 一.fs模块的使用: 1.文件操作: 读文件: //读文件 var fs=require('fs'); ...

  3. 不要在nodejs中阻塞event loop

    目录 简介 event loop和worker pool event loop和worker pool中的queue 阻塞event loop event loop的时间复杂度 Event Loop中 ...

  4. NodeJS 模块开发及发布详解

    NodeJS 是一门年轻的语言,扩展模块并不太全,经常我们想用某个模块但是却找不到合适的.比如前两天我需要使用hmac和sha1来做签名,就没有找到一个比较好用的模块,这时候就需要我们自己来实现相应的 ...

  5. NodeJS模块、包、NPM

    1.NodeJS模块        每一个Nodejs都是一个NodeJS模块,包括JS文件,JSON文本文件,二进制模块文件. a.模块的应用               新建一个文件mytest. ...

  6. # nodejs模块学习: express 解析

    # nodejs模块学习: express 解析 nodejs 发展很快,从 npm 上面的包托管数量就可以看出来.不过从另一方面来看,也是反映了 nodejs 的基础不稳固,需要开发者创造大量的轮子 ...

  7. nodejs模块xml2js解析xml的坑

    在一个项目中,用到nodejs模块xml2js解析xml,xml的数据如下: <xml> <MsgId>6197906553041859764</MsgId> &l ...

  8. NodeJS 模块&函数

    NodeJS 模块&函数 nodejs的多文件操作通过模块系统实现,模块和文件一一对应.文件本身可以是javascript代码.JSON或编译过的C/C++扩展 基本用法 nodeJS通过ex ...

  9. es6模块 nodejs模块和 typescript模块

    es6模块 import和export nodejs模块 require和module.exports typescript模块 module和export

随机推荐

  1. UIView的endEditing:方法

    当视图收到endEditing:消息时,如果视图(或者其下的人和子视图)是当前的第一响应对象,就会取消自己的第一响应对象状态, 而且虚拟键盘也会消失(传入的参数代表是否需要强制取消第一响应对象状态.有 ...

  2. smarty、smarty格式化、smarty整数、smarty float、smarty各种转换方式、smarty日期转换等等 (转)

    <? require("setup.php"); define('PAGETITLE','pagtitle'); function insert_top($lid,$sid) ...

  3. is_callable — 检测参数是否为合法的可调用结构

    说明 bool is_callable ( callable $name [, bool $syntax_only = false [, string &$callable_name ]] ) ...

  4. linux下OpenSSL的RSA密钥生成

    工具的安装: 一.源码安装 OpenSSL Version:openssl-1.0.0e.tar.gz ------------------------安装: 1.将下载的压缩包放在根目录, 2.在文 ...

  5. Android linux kernel privilege escalation vulnerability and exploit (CVE-2014-4322)

    In this blog post we'll go over a Linux kernel privilege escalation vulnerability I discovered which ...

  6. OpenOffice/LibreOffice的行距问题

    OpenOffice和LibreOffice的默认行距(行间距)都很宽,可以通过以下方法设置. 格式 -> 页面 -> 文字网格 -> 不使用网格

  7. synchronized是什么

        在再有人问你Java内存模型是什么,就把这篇文章发给他中我们曾经介绍过,Java语言为了解决并发编程中存在的原子性.可见性和有序性问题,提供了一系列和并发处理相关的关键字,比如synchron ...

  8. 关于html的小bug

    废话不说 看代码 因为最近比较忙  所以不闲聊了啊 <!DOCTYPE html> <html lang="en"> <head> <me ...

  9. ios8 一些运行问题

     iOS10相册相机闪退bughttp://www.jianshu.com/p/5085430b029fiOS 10 因苹果健康导致闪退 crashhttp://www.jianshu.com/p/5 ...

  10. Web存储使用详解(本地存储、会话存储)

    Web存储使用详解(本地存储.会话存储)1,Web存储介绍HTML5的Web存储功能是让网页在用户计算机上保存一些信息.Web存储又分为两种:(1)本地存储,对应 localStorage 对象.用于 ...