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:this.timerID = setInterval(this.loadData, 1000);
- so, this inside functionloadData
to be given in the timer will no longer be the object of the expected class.$.ajax({ success: function(result) {
- in this casethis
Change again. ajax♪
There may be several decisions:
- remain relevant
this
before challenge and use inside thisand retained variable - Use https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function/bind transfer
Use https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/Arrow_functions
this.loadData = () => { $.ajax({ success: (result) => { ... this.updateData(jsonObj); } }); };