我正在将一些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未定义”。< / p>
我应该做些什么?
编辑 - 这是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并不是那么好。
答案 0 :(得分:2)
D'哦。愚蠢的错误。当我从javascript转换为coffeescript时,我搞砸了ajax调用。
$.ajax {url: "#{window.location.pathname}?time=#{Date.now()}"}, success
应该是:
$.ajax {url: "#{window.location.pathname}?time=#{Date.now()}", success: success}
对不起,大家。