Return / Scope problems in CoffeeScript / Javascript

0

I have in Rails a get '/estados_por_pais/:pais_id route that returns me a JSON array with states in this country. This works perfectly.

I created a CoffeeScript class with a static method that should fetch this array of states:

class window.Municipio

  @busca_estados_por_pais: (pais_id) ->
    retorno = 1
    $.get "/estados_por_pais/#{ pais_id }", (estados) ->
      retorno = estados
      #debug
      alert estados
      alert retorno
      return
    retorno

Here's the Javascript output:

(function() {
  window.Municipio = (function() {
    function Municipio() {}

    Municipio.busca_estados_por_pais = function(pais_id) {
      var retorno;
      retorno = 1;
      $.get("/estados_por_pais/" + pais_id, function(estados) {
        retorno = estados;
        alert(estados);
        alert(retorno);
      });
      return retorno;
    };

    return Municipio;

  })();

}).call(this);

In this case, the outputs of alert(estados) and alert(retorno) are exactly as expected, that is, an array of objects.

However, the method return is 1 , and the retorno variable is not being redeclared within the scope of the jQuery function.

    
asked by anonymous 02.05.2014 / 16:30

1 answer

1

The problem is that $.get is an asynchronous function, so its busca_estados_por_pais method returns before the result of the ajax request arrives. The most recommended solution is to restructure your code to use callbacks:

class window.Municipio

  @busca_estados_por_pais: (pais_id, callback) ->
    $.get "/estados_por_pais/#{ pais_id }", (estados) ->
      callback(estados)

In the method call, you will need to pass a function (the callback) that will be executed when the result of the request is available.

    
02.05.2014 / 17:22