【问题标题】:Explanation of Node.js event emitter source codeNode.js事件发射器源码说明
【发布时间】:2016-02-27 06:20:47
【问题描述】:

我正在查看 Node.js 事件发射器的源代码

https://github.com/nodejs/node/blob/master/lib/events.js

我试图弄清楚代码是如何识别函数的,特别是在使用addListener/removeListener

这些函数都接受 (String s, Function f) 的签名

但我不明白的是,当调用 removeListener 时,它们如何识别要删除的函数,因为可能有多个函数用作同一事件的回调。

我想我特别想知道这条线是怎么回事

list[i] === listener

也就是说,比较两个函数是否相等,在 JS 中起作用

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    但我不明白的是他们如何识别要使用的功能 调用 removeListener 时删除,因为可能有多个 作为同一事件的回调函数。

    eventEmitter 对象(或从它继承的任何对象)存储了它正在为其管理侦听器的所有事件名称的映射。然后它可以为地图中的每个事件名称存储一组函数。 addListener() 将一个函数添加到右侧列表中,removeListener() 从右侧列表中删除匹配的函数。当你这样做时:

    obj.addListener("someEvent", someFunction);
    

    eventEmitter 对象确保“someEvent”位于它所管理的事件名称映射中,并将 someFunction 添加到该特定事件名称的侦听器数组中。对于给定的事件名称,可以有多个侦听器,因此只要有多个侦听器,eventEmitter 就会使用一个数组,因此它可以存储该特定事件的所有侦听器函数。

    addListener()removeListener() 的代码都相当复杂,因为两者都实现了优化,这使得代码更难遵循。如果给定事件有多个侦听器,则代码在事件映射中存储一组侦听器函数。但是,如果只有一个监听器,那么它只存储一个监听器(无数组)。这意味着任何使用侦听器列表的代码都必须首先检查它是单个侦听器还是侦听器数组。

    removeListener() 有两个参数,一个事件类型和一个函数。目标是为注册该特定函数的该事件找到一个先前注册的侦听器并将其删除。

    发射器对象本身为每种类型的事件存储一个函数数组。因此,当调用removeListener(type, listener) 时,调用者将传入事件类型和特定函数。 eventEmitter 代码将在其数据中查找传入的特定类型事件的侦听器列表,然后在该侦听器列表中搜索与传入的特定侦听器匹配的侦听器。如果找到,它将被删除。

    这是一个带注释的代码副本,应该解释 removeListener() 函数中每个代码块中发生的事情:

    // emits a 'removeListener' event iff the listener was removed
    EventEmitter.prototype.removeListener =
        function removeListener(type, listener) {
          var list, events, position, i;
    
          // make sure that listener was passed in and that it's a function
          if (typeof listener !== 'function')
            throw new TypeError('"listener" argument must be a function');
    
          // get the map of events we have listeners for
          events = this._events;
          if (!events)
            return this;
    
          // get the list of functions for the specific event that was passed in
          list = events[type];
          if (!list)
            return this;
    
          // handle some special cases when there is only one listener for an event
          if (list === listener || (list.listener && list.listener === listener)) {
            if (--this._eventsCount === 0)
              this._events = {};
            else {
              delete events[type];
              if (events.removeListener)
                this.emit('removeListener', type, listener);
            }
          } else if (typeof list !== 'function') {
            // when not a special case, we will have to find the right
            // function in the array so initialize our position variable
            position = -1;
    
            // search backward through the array of functions to find the
            // matching function
            for (i = list.length; i-- > 0;) {
              if (list[i] === listener ||
                  (list[i].listener && list[i].listener === listener)) {
                position = i;
                break;
              }
            }
    
            // if we didn't find it, nothing to do so just return
            if (position < 0)
              return this;
    
            // if the list has only one function in it, then just clear the list
            if (list.length === 1) {
              list[0] = undefined;
              if (--this._eventsCount === 0) {
                this._events = {};
                return this;
              } else {
                delete events[type];
              }
            } else {
              // remove that one function from the array
              spliceOne(list, position);
            }
    
            // send out an event if we actually removed a listener
            if (events.removeListener)
              this.emit('removeListener', type, listener);
          }
    
          return this;
        };
    

    添加了基于 cmets 的解释:

    Javascript 中的函数是第一类对象。当代码使用===== 比较两个函数或比较变量与函数引用时,Javascript 只是比较每个操作数是否引用相同的底层Javascript 对象。这里没有使用.toString()。这只是测试它们是否指的是同一个物理对象。

    这里有几个例子:

    function myFunc() {
       console.log("hello");
    }
    
    var a = myFunc;
    if (a === myFunc) {
        console.log("Yes, a does refer to myFunc");
    }
    
    var b = a;
    if (b === a) {
        console.log("Yes, a and b refer to the same function");
    }
    
    function myFunc2() {
       console.log("hello");
    }
    
    a = myFunc;
    b = myFunc2;
    
    if (a !== b) {
        console.log("a and b do not refer to the same function");
    }
    

    或者,更像是在工作的 sn-p 中 addListener()removeListener() 中使用的内容:

    function myFunc() {
       console.log("hello");
    }
    
    var list = [];
    log("Items in list initially: " + list.length);
    list.push(myFunc);
    log("Items in list after adding: " + list.length);
    
    // search through list to find and remove any references to myFunc
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i] === myFunc) {
             list.splice(i, 1);
        }
    }
    
    log("Items in list after find/remove: " + list.length);
    
    // helper function to log output
    function log(x) {
        var div = document.createElement("div");
        div.innerHTML = x;
        document.body.appendChild(div);
    }

    【讨论】:

    • 谢谢!我想知道“list[i] === listener”在比较函数时是如何工作的——看起来他们正在使用 === 来比较函数......但是这在 JS 中实际上是如何工作的?我认为 JS 中的对象/函数没有任何类型的 id?
    • 比较两个函数f1 === f2时,JS是否对每个函数做一个toString()然后比较?出于多种原因,这似乎很糟糕。
    • @AlexMills - 函数是 Javascipt 中的第一类对象。因此,在这种情况下,=== 只是比较两个操作数是否引用了相同的确切函数。在 javascript 中,你可以这样做:function myFunc() {...}; var fn = myFunc; if (fn === myFunc) {...}。这就是这里发生的一切。函数只是一个对象引用,就像 JS 中的任何其他对象引用一样。
    • @AlexMills - 不,它不执行.toString()。它比较它们是否在物理上引用相同的底层 Javascript 对象。就像:var a = {greeting: "hello"}; var b = a; if (b === a) {...};
    • @AlexMills - 请参阅我添加到答案末尾的示例。
    【解决方案2】:

    代码通过类似下面的比较找到函数:

    var events = [/*...*/];
    function removeListener(type, fn){
        for(var z = 0; z < events.length; z++){
             if(events[z] === fn){
                 // fn event listener is equal to
                 // the zth element of events, so
                 // remove this element
             }
        }
    }
    

    【讨论】:

    • 但是,这实际上并不是实际的 eventEmitter 代码所做的。这个问题的答案应该解释实际的 eventEmitter 代码的作用,而不是 removeListener 函数在理论上是如何工作的。
    • @jfriend00 这几乎就是removeListener 代码的作用。在一个小的、最小的示例中可能比整个代码转储更容易理解
    【解决方案3】:

    addListenerremoveListener 要求您传入一个函数。该函数被存储在一个字典中,该字典将特定事件映射到为该事件注册的函数。

    为了使removeListener 工作,您必须传入传递给addListener相同 函数。了解在 JavaScript 中,函数是一等公民。简单来说,这意味着您可以将函数分配给变量并将函数作为参数传递给其他函数。

    这是一个使用addListener,然后使用removeListener 删除的示例,

    var cb = function() {
      console.log('event emitted');
    }
    
    emitter.addListener('event', cb);
    
    // We can then remove the association by passing in cb as the
    // second argument to removeListener
    emitter.removeListener('event', cb);
    

    或者,我们可以使用命名函数来避免将函数分配给变量。

    emitter.addListener('event', function cb() {
      console.log('event emitted');
    });
    
    // Remove
    emitter.removeListener('event', cb);
    

    由于函数是一等公民,因此可以直接存储和比较它们。使用它,removeListener 只需迭代其内部列表,直到找到特定的函数对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      相关资源
      最近更新 更多