Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ee-first源码分析 #3

Open
brunoyang opened this issue Sep 26, 2015 · 0 comments
Open

ee-first源码分析 #3

brunoyang opened this issue Sep 26, 2015 · 0 comments

Comments

@brunoyang
Copy link
Owner

仓库:https://github.com/jonathanong/ee-first

ee-first是一个竞争事件收集器,可以为多个事件对象绑定多个事件,并在某个事件触发后移除该对象的所有事件。

本文根据ee-first@1.1.1版本所撰写。

使用方法

'use strict';
const first = require('ee-first');

const event = require('events').EventEmitter;
const ee1 = new event();
const ee2 = new event();

const handle1 = first([[ee1, 'error', 'a', 'b']], function(err, ee, event, args) {
 console.log(`err: ${err}\nee: ${ee}\nevent: ${event}\nargs: ${args}`);
})

const handle2 = first([[ee2, 'error', 'a', 'b']], function(err, ee, event, args) {
 console.log(`err: ${err}\nee: ${ee}\nevent: ${event}\nargs: ${args}`);
})

ee1.emit('error', 'err msg'); 
// err: err msg
// ee: [object Object]
// event: error
// args: err msg


ee1.emit('b', 'whatever'); // nothing

// 移除所有绑定在ee2事件对象上的事件
handle2.cancel();

ee2.emit('b', 'sucks'); // also nothing

源码分析

这个模块暴露了一个first方法,这个方法接受2个参数,事件数组和回调。事件数组是指一个二维数组,可以包含若干个数组,每个数组的第一个是元素是事件对象,如httpnet等继承自EventEmitter的对象。剩余的元素是所有需要绑定在该事件对象上的事件。第二个参数是事件绑定的回调,在这里为了便于区分,特称为事件回调

cleanups数组是一个包含所有事件对象所绑定事件的数组。

进入循环后,变量fnlistener函数的返回值,listener的作用是收集事件回调的参数列表,并传入callback函数,等待事件触发(emit)。callback函数做了两件事,执行cleanup方法移除所有cleanups数组中事件对象中的事件,并执行回调,这就表现竞争现象

cancel方法直接调用cleanup,移除所有事件。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant