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"
      }
    }
  });
};

削除キーをクリーンアップして自由に使用した後、これが私のcoffeescriptです。

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 で関数を正常にトリガーできますが、coffeescript バージョンではエラーが発生します:「ReferenceError: check_quiz_state が定義されていません」。

どうすればいいですか?

編集 - コーヒースクリプトが出力しているものは次のとおりです。申し訳ありませんが、私の心を滑らせました:

(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 に答える