Coffeescript/Javascript return/scope problems

Asked

Viewed 114 times

0

I’ve got a route in the Rails get '/estados_por_pais/:pais_id which returns me a JSON array with states of this country. This works perfectly.

I created a Coffeescript class with a static method that should seek to return 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 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 exits from alert(estados) and alert(retorno) is exactly the expected, ie an array of objects.

But the return of the method is 1, where the variable retorno is not being redeclared within the scope of jQuery’s function.

1 answer

1


The problem is that $.get is an asynchronous function, and therefore its method busca_estados_por_pais 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 request result is available.

  • Callback is even recommended. Another alternative would be to make the request synchronously, but this would "crash" the browser. (I researched it briefly after your reply) =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.