Coffeescript回调范围问题

时间:2013-07-03 01:40:33

标签: coffeescript hubot

您好我正在尝试为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)

1 个答案:

答案 0 :(得分:2)

这几乎肯定是最后一行的空白问题。三重检查您是否在整个文件中使用了一致的缩进,并确保您的文件在msg.send "Fork Complete..."之后有最终换行符。我复制并粘贴了你的coffeescript代码并将其编译为javascript,并且最后msg.send行正确地将inside行正确地放入{{1}}正确的函数,而上面的js将该行放在错误的位置。

相关问题