理解用于emit函数esp的Node.js代码



我很难完全掌握下面的代码。我想了解emit的工作情况。

以下是我对下面代码中提到的所有发射实例的理解。

  1. profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));

它执行错误功能。(但我不确定代码中错误函数的定义。

  1. response.on('data', function (chunk) { body += chunk; profileEmitter.emit("data", chunk); });

这会发出上面定义的数据事件函数。一切都好!但第二个参数是什么呢。根据文档,这个参数应该是一个监听器,但它只是一个参数——在数据之前定义的"匿名函数"。

  1. try { //Parse the data var profile = JSON.parse(body); profileEmitter.emit("end", profile); } catch (error) { profileEmitter.emit("error", error); }

try块中的第一个发射这次有一个profile变量。catch块中的第二个发射具有error作为第二个arg。好大家都很困惑。

var EventEmitter = require("events").EventEmitter;
var http = require("http");
var util = require("util");

function Profile(username) {
EventEmitter.call(this);
profileEmitter = this;
//Connect to the API URL (http://teamtreehouse.com/username.json)
var request = http.get("http://example.com/" + username + ".json", function(response) {
    var body = "";
    if (response.statusCode !== 200) {
        request.abort();
        //Status Code Error
        profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
    }
    //Read the data
    response.on('data', function (chunk) {
        body += chunk;
        profileEmitter.emit("data", chunk);
    });
    response.on('end', function () {
        if(response.statusCode === 200) {
            try {
                //Parse the data
                var profile = JSON.parse(body);
                profileEmitter.emit("end", profile);
            } catch (error) {
                profileEmitter.emit("error", error);
            }
        }
    }).on("error", function(error){
        profileEmitter.emit("error", error);
    });
});
}
util.inherits( Profile, EventEmitter );
module.exports = Profile;

EventEmitter.emit()函数只说明它所说的内容:它将事件发送给为所述事件注册的侦听器。

第一个参数(事件类型)之后的参数只是事件的参数,它们不是监听器。

因此,您的第一个调用只发送一个error事件,并附带一个描述错误的Error参数。

第二个调用发送一个data事件,以及刚刚接收到的数据块。

第三个调用发送end事件以及解码的配置文件。

最后一个调用发送一个error事件,以及从catch接收到的错误。

EventEmitter的所有概念与java中的Observer pattern相同(如果您来自java世界),您可以观察您对示例data事件感兴趣的事件,并且每次您通过emit('data', {data})发出data事件时,它都将由通过on('data', handlerfunction)订阅事件的事件处理程序处理。

error是nodejs中的一个特殊事件,如果你不处理它,它只会破坏你的进程。

最新更新