【发布时间】:2015-12-01 08:22:53
【问题描述】:
我很难完全掌握下面的代码。我想了解emit的工作原理。
这是我对下面代码中提到的所有发射实例的理解。
profileEmitter.emit("error", new Error("There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"));
它执行错误函数。(但我不确定代码中哪里定义了错误函数。
response.on('data', function (chunk) { body += chunk; profileEmitter.emit("data", chunk); });
这会发出一个如上定义的数据事件函数。一切都好!但是第二个参数是什么。根据文档,这个参数应该是一个监听器,但它只是一个参数——在数据之前定义的“匿名函数”。
try { //Parse the data var profile = JSON.parse(body); profileEmitter.emit("end", profile); } catch (error) { profileEmitter.emit("error", error); }
try 块中的第一个发射这次有一个profile 变量。
catch 块中的第二个发射具有 error 作为第二个参数。好 !都糊涂了。
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;
【问题讨论】:
-
response.on('data', …)不发出“数据侦听器函数”。不知道你的意思。 -
糟糕!它应该是数据事件,然后是侦听器函数。我会纠正这个问题。谢谢!
标签: javascript node.js