3

我正在将一些javascript 转换为coffeescript,并且无法访问我定义的函数。这是原始的工作javascript(我也在使用jQuery):

function check_quiz_state(){
  var div = $('#quiz-waiting');
  var timestamp = new Date().getTime();

  $.ajax({
    url: window.location.pathname + "?time=" + timestamp,
    success: function(state) {
      if (state == 'created' || state == 'completed') {
        setTimeout("check_quiz_state()", 3000);
      }
      else if (state == 'built') {
        div.html("<a href='" + window.location.pathname + "/pages/1'>Click to begin!</a>");
      }
      else if (state == 'graded') {
        window.location.pathname = window.location.pathname + "/review"
      }
    }
  });
};

在对删除键进行一些清理和自由使用之后,这是我的咖啡脚本:

check_quiz_state = ->
  success = (state) ->
    switch state
      when 'created', 'completed' then setTimeout "check_quiz_state()", 3000
      when 'built' then $('#quiz-waiting').html "<a href='#{window.location.pathname}/pages/1'>Click to begin!</a>"
      when 'graded' then window.location.pathname = window.location.pathname + "/review"

  $.ajax {url: "#{window.location.pathname}?time=#{Date.now()}"}, success

问题在于使用 setTimeout 使函数重复 - 这在原始 javascript 中可以正常工作,但对于 coffeescript 它没有。我认为它无法找到 check_quiz_state 函数 - 如果我在 Chrome 中使用 javascript 控制台,我可以用我原来的 javascript 触发该函数,但是使用咖啡脚本版本我得到一个错误:“ReferenceError:check_quiz_state 未定义”。

我应该做些什么不同的事情?

编辑 - 这是 coffeescript 输出的内容。对不起,我的脑子里闪过:

(function() {
  var check_quiz_state;
  $(function() {
    // Other application code I omitted above, which is calling check_quiz_state() successfully.
  });
  check_quiz_state = function() {
    var success;
    success = function(state) {
      switch (state) {
        case 'created':
        case 'completed':
          return setTimeout("check_quiz_state()", 3000);
        case 'built':
          return $('#quiz-waiting').html("<a href='" + window.location.pathname + "/pages/1'>Click to begin!</a>");
        case 'graded':
          return window.location.pathname = window.location.pathname + "/review";
      }
    };
    return $.ajax({
      url: "" + window.location.pathname + "?time=" + (Date.now())
    }, success);
  };
}).call(this);

我猜它包含的功能是为什么我不能从 Chrome 开发者控制台调用它,但我不明白为什么超时失败。不过,我对 javascript 不是很好。

4

1 回答 1

2

哦。愚蠢的错误。当我从 javascript 翻译到 coffeescript 时,我搞砸了 ajax 调用。

$.ajax {url: "#{window.location.pathname}?time=#{Date.now()}"}, success

应该:

$.ajax {url: "#{window.location.pathname}?time=#{Date.now()}", success: success}

对不起,大家。

于 2011-02-20T05:21:55.350 回答