您好,我正在尝试为 hubot 编写插件脚本。我似乎对范围界定有问题。 fork 回调中“msg”的引用未定义,我似乎没有在回调中获得任何变量。
内置的 jira-issues.coffee 也遇到了同样的问题!昨天在该脚本中,jiraUrl 在回调中未定义。今天早上它又开始工作了,现在它又停止工作了(在我重新启动 hubot 之后)。我什至从未修改过它。
有没有人遇到过这样的事情?
githubApi = require("node-github")
module.exports = (robot) ->
github = new githubApi { "version": "3.0.0" }
github.authenticate { "type":"basic", "username":process.env.HUBOT_GITHUB_USER, "password":process.env.HUBOT_GITHUB_P
ASSWORD }
robot.respond /kickstart\s(\S+)/i, (msg) ->
name = msg.match[1]
msg.send name
base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com'
github.repos.fork {"user":"Raven", "repo":"Raven","org":"codedemos"}, (err,data) ->
if err
msg.send "error :("
else
msg.send "Fork Complete..."
编译为
// Generated by CoffeeScript 1.6.3
(function() {
var githubApi;
githubApi = require("node-github");
module.exports = function(robot) {
var github;
github = new githubApi({
"version": "3.0.0"
});
github.authenticate({
"type": "basic",
"username": process.env.HUBOT_GITHUB_USER,
"password": process.env.HUBOT_GITHUB_PASSWORD
});
return robot.respond(/kickstart\s(\S+)/i, function(msg) {
var base_url, name;
name = msg.match[1];
msg.send(name);
base_url = process.env.HUBOT_GITHUB_API || 'https://api.github.com';
return github.repos.fork({
"user": "Raven",
"repo": "Raven",
"org": "codedemos"
}, function(err, data) {
var id;
if (err) {
return msg.send("error :(");
} else {
return id = data.id;
}
});
});
};
msg.send("Fork Complete...");
}).call(this);
看起来不错,但运行它会产生:
ReferenceError: msg is not defined
at Object.<anonymous> (/opt/kbot/scripts/kickstart.coffee:48:2, <js>:36:3)
at Object.<anonymous> (/opt/kbot/scripts/kickstart.coffee:33:1, <js>:38:4)
at Module._compile (module.js:456:26)
最佳答案
这几乎可以肯定是最后一行的空白问题。三重检查您是否在整个文件中使用了一致的缩进,并确保您的文件在 msg.send "Fork Complete..."
之后有一个最后的换行符。我复制并粘贴了你的 coffeescript 代码并将其编译为 javascript,最后 msg.send
行被正确地放入 inside
正确的函数,而你上面的 js 中有该行错误的地方。
关于Coffeescript 回调范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17438429/