I'm converting some javascript to coffeescript, and I'm having trouble accessing a function I've defined. Here's the original working javascript (I'm also using 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"
}
}
});
};
After some cleanup and liberal use of the delete key, here's my 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
The problem is with using setTimeout to make the function repeat - this works fine in the original javascript, but with the coffeescript it doesn't. I think it's unable to find the check_quiz_state function - if I use the javascript console in Chrome I can trigger the function just fine with my original javascript, but with the coffeescript version I get an error: "ReferenceError: check_quiz_state is not defined".
What should I be doing differently?
Edit - Here's what coffeescript is outputting. Sorry, slipped my mind:
(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>"开发者_如何学C);
case 'graded':
return window.location.pathname = window.location.pathname + "/review";
}
};
return $.ajax({
url: "" + window.location.pathname + "?time=" + (Date.now())
}, success);
};
}).call(this);
I guess the function it's wrapped in is why I can't call it from the Chrome developer console, but I don't get why the timeout is failing. I'm not that great with javascript, though.
D'oh. Stupid mistake. I screwed up the ajax call when I was translating from javascript to coffeescript.
$.ajax {url: "#{window.location.pathname}?time=#{Date.now()}"}, success
Should be:
$.ajax {url: "#{window.location.pathname}?time=#{Date.now()}", success: success}
Sorry, everyone.
精彩评论