Ajax调用后事件绑定时看到未定义的类对象

时间:2018-04-16 02:08:59

标签: javascript jquery html json ajax

第一篇文章,呜!看了很多,但找不到解决方案。感谢您的关注和时间。我在这里有一个类实例,其中包含一个数组,我使用基于ajax调用的JSON数据填充对象。我想将一个将数组呈现为HTML的函数绑定到HTML按钮元素。

在实例化和ajax调用完成后使用when(),我可以调用实例的属性,甚至执行该函数。但是当我尝试将相同的函数绑定到HTML按钮单击事件时,当我触发事件时,该函数引用未定义的'theStats'对象。

$(function () 
{
// Main Stats Object
var theStats = new Stats();
var initPop = theStats.populate();

$.when(initPop).done(function(a1)
{
    // Returns defined instance property
    console.log(theStats.arr.length);
    // Function works properly 
    theStats.render();

    // Why does this bind to an undefined 'theStats', when it executed
    // only when the ajax call, as well as object construction is complete?
    $("#render-stats").on("click", theStats.render);
});
});

我认为这是我对异步如何工作的误解?我也在研究事件委托,但是我不是在创建一个新的HTML元素,而是一个基于ajax的Object。任何和所有反馈都非常感谢(包括我的代码实践,呵呵)。如果我错过了类似的解决方案,或者我误解了如何堆栈溢出,请告诉我。再次感谢!

 class Stats 
   {

constructor()
{
    // Creates Array for Stat Objects
    this.arr = [];  
}

/* Populate method requests thru ajax the JSON on the server on execution and 
    populates this current Stats object's array 
*/
populate()
{
    var that = this;
    var ajaxGet = $.get("php/get.php",
    function(jsonData, status)
    {
        var obj = JSON.parse(jsonData);
        for (let key in obj)
        {
            var newStat = new Stat(obj[key].id, obj[key].distance, obj[key].date);
            that.arr.push(newStat);
        } 
        this.arr = that.arr;
        console.log("Ajax Complete: " + this.arr);
    });
    return ajaxGet;
}


/* Render method creates HTML elements and renders them to the page using the data currently stored 
    within this particular Stats object */
render()
{
    $("#test").text("");

    for (let i = 0; i < this.arr.length; i++)
    {
        $("#test").append("<li class='runStat'> Run Number: " + this.arr[i].id + ", Distance: " + this.arr[i].distance + ", on Date: " + this.arr[i].date + "</li> <br/>");
    }
}
}

0 个答案:

没有答案