Problem accessing a function defined in Coffeescript

I am converting some javascript to coffeescript and I am having problems accessing the function that I defined. Here's the original working javascript (I also use 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 cleaning and liberal use of the delete key, here is my coffee pot:

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 using setTimeout to repeat the function - this works fine in the original javascript, but this is not the case with coffee lettering. I think he cannot find the check_quiz_state function - if I use the javascript console in Chrome, I can just call the function with my original javascript, but with the coffeescript version I get the error: "ReferenceError: check_quiz_state not defined".

What should I do differently?

- . , :

(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.

+3
1

D'. . ajax, javascript coffeescript.

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

:

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

, .

+2

Source: https://habr.com/ru/post/1793316/


All Articles