Brauser cannot find a function in ajax processor.



  • I've been struggling for five hours and I can't figure out what the problem is. There is a class in which data uploading and updating techniques and methods for starting and stopping the timer are implemented. The timer gives rise to the downloading function of the data(loadData) in which data are downloaded through ajax, the function of updating the data(updateData) is called, and the problem here is that the browser can somehow find this function of "main.js:14 Uncaught TypeError: this.updateData is not a function."

    function Runnable()
    {
        this.timerID;
        this.loadData = function() {
            $.ajax({
                type: "POST",
                url: "ajax_handler.php",
                success: function(result) {
                    try {
                        jsonObj = $.parseJSON(result);
                    } catch (e) {
                        alert('Ошибка на сервере!');
                    }
                    //ВОТ ЗДЕСЬ ПРОБЛЕМА, ЭТА ФУНКЦИЯ НЕ НАЙДЕНА
                    this.updateData(jsonObj);
                }
            });
        };
    
    this.updateData = function(events) {
        var countNewData = $(events).size();
        for (var i = 0; i < countNewData; i++) {
            $($('[id ^= "event_"]')[$('[id ^= "event_"]').size() - 1]).remove();
            $('#wrap').prepend('<div id="event_' + (countNewData - i) + '">' + events[i] + '</div>' );
        }
    };
    
    this.startTimer = function() {
        this.timerID = setInterval(this.loadData, 1000);
    };
    
    this.stopTimer = function() {
        clearInterval(this.timerID);
    };
    

    }

    $(document).ready( function() {
    var r = new Runnable();
    r.startTimer();
    });



  • In Javakrit this Depends on how the function has been declared and how it is called. Details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    Specifically in question code this Changes twice:

    1. this.timerID = setInterval(this.loadData, 1000); - so, this inside function loadData to be given in the timer will no longer be the object of the expected class.

    2. $.ajax({ success: function(result) { - in this case this Change again. ajax

    There may be several decisions:

    1. remain relevant this before challenge and use inside thisand retained variable
    2. Use https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind transfer
    3. Use https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions

      this.loadData = () => {
          $.ajax({
              success: (result) => {
                  ...
                  this.updateData(jsonObj);
              }
          });
      };
      



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2