当我在淘汰赛中从服务器加载数据时未定义的对象

undefined object when i load data from server in knockout

我在 knockout 中从服务器控制器加载了一个列表并正确接收了该列表,我也打印了该列表,但是当将此数据放入多个 table html 时,出现错误提示"Uncaught TypeError: Cannot read property 'push' of undefined"...

但是如果我在按钮功能中单击,一切正常,但我不需要按任何按钮就需要它。

<!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());

所以...我需要在开头推送此列表,有人帮忙吗?

因为你get方法中的this并不是你想的this。您可以在 this.allItems = ko.observableArray([]); 之前将 this 分配给 self,例如 var self = this;,并在您的 get 方法中使用 self.allItems 而不是 this.allItems