温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - undefined object when i load data from server in knockout
html java javascript knockout.js spring

javascript - 当我从敲除中的服务器加载数据时,未定义的对象

发布于 2020-05-07 02:11:23

我从淘汰赛中的服务器控制器加载列表并正确接收该列表,我也打印了该列表,但是当将此数据放入多表html中时,出现错误,提示“未捕获的TypeError:无法读取未定义的属性'push'” ...

但是,如果我在按钮功能单击中执行此操作,一切正常,但是我需要不按任何按钮。

<!DOCTYPE html>
<html>
    <head>
        <tittle> <h1>Customers </h1></tittle>

    </head>

    <body>

        <button  data-bind="click: addItem">Add</button>
        <p>List Names:</p>
        <select multiple="multiple" height="8" data-bind="options:allItems"> </select>

        <script type="text/javascript" src="/lib/knockout-3.5.0.js"></script>
        <script src="/lib/jquery-3.4.1.js"></script>
        <script src="/js/prueba.js"></script>   

    </body>

</html>

这是.js

function ViewModel(){

    this.allItems= ko.observableArray([]);
    var list=[];

    $.get("/customers", function(data) { 

        for(var i=0; i<data.length; i++){
            list[i]={name:data[i].name, lastname:data[i].lastname};
            alert(list[i].name);
            alert(list[i].lastname);
        }

        console.log(this.allItems); // here "allItems" is undefined
        this.allItems.push(list[0].name); //error
    });

    this.addItem= function(){

            console.log(this.allItems); // here "allItems" is not undefined
            this.allItems.push(list[0].name); //ok


    };

};

ko.applyBindings(new ViewModel());

所以...我需要一开始就推送此列表,有人帮忙吗?

查看更多

提问者
guilieen
被浏览
27
Gawel1908 2020-02-18 21:21

因为您的this输入get方法不是this您认为的。您可以分配thisselfvar self = this;之前this.allItems = ko.observableArray([]);和你的get方法使用self.allItems代替this.allItems