M
M
Michael2014-12-03 15:07:18
JavaScript
Michael, 2014-12-03 15:07:18

How to return a value from a nested function?

hello there is a function

class ShowReaders
  constructor:(@listreaderdiv, @currentreaderdiv )->
       console.log('mainclass')
       @currentReader
       @testedReaders

...
...



  getCurrentReader:(url)->
       $.post "/ajax/#{url}", (data)->
            console.log('data ',data['current'])
            @currentReader = data['current']



  create:->
       @getCurrentReader('getcurrentreader')
       $('#currentreader').empty()
       console.log( @currentReader)

The question is why, when assigning the value of the currentReader variable in the getCurrentReader method, the variable is nominally assigned, and when called in the create method, it already returns undefine.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Puzynya, 2014-12-03
@nextel

Have you been doing asynchronous programming for a long time or just started today?
Because you need at least this (sorry, not strong in coffescript, I wrote it as best I could):

class ShowReaders
  constructor:(@listreaderdiv, @currentreaderdiv )->
       console.log('mainclass')
       @currentReader
       @testedReaders

...
...



  getCurrentReader:(url, callback)->
       $.post "/ajax/#{url}", (data)->
            console.log('data ',data['current'])
            @currentReader = data['current']
            @onGetCurrentReader()

  create:->
       @getCurrentReader('getcurrentreader')

  onGetCurrntReader:->
      $('#currentreader').empty()
      console.log( @currentReader)

The following seems to me the most logical option:
function ShowReaders() {
  this.currentReader = null;
  this.testedReaders = null;
}

ShowReaders.prototype.getCurrentReader = function(url, callback) {
  $.post(url, this.onGetCurrentReader.bind(this, callback));
};

ShowReaders.prototype.onGetCurrentReader = function(callback) {
  this.currentReader = data['current'];
  callback();
};

ShowReaders.prototype.create = function() {
  this.getCurrentReader('getcurrentreader', function() {
    $('#currentreader').empty();
    console.log(this.currentReader)
  }.bind(this));
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question