【发布时间】:2018-08-23 10:49:28
【问题描述】:
我根本无法掌握数据绑定的 knockout.js 概念,因此寻求新手帮助。
有趣的是,代码实际上正在做我想做的事。我只是不明白为什么:
HTML
<div class = "gridStyle2" data-bind="koGrid: gridOptions"></div>
JS
$.getJSON('http://127.0.0.1:8000/home/players/', function(playerdata) {
var self = this;
this.myData = ko.observableArray(playerdata);
this.mySelectedData = ko.observableArray([]);
this.gridOptions = { data: self.myData,
columnDefs: [{ field: 'ShortName', displayName: 'Name', width: 100 },
{ field: 'CurrentVal', displayName: 'Value', width: 70 },
{ field: 'ShortClub', displayName: 'Club', width: 60 },
{ field: 'ShortPos', displayName: 'Position', width: 70 },
],
selectedItems: this.mySelectedData,
};
ko.applyBindings(self, document.getElementById('newgrid'));
});
问题
所以我的 JSON 数据很好地显示在“koGrid”中。但是,当我尝试复制代码以使用不同的 JSON 数据源创建不同的表时,这些表不会显示。
我的数据绑定应该查看“gridOptions”吗?它不应该是一个变量吗?每当我尝试将上述 JS 放入变量或函数中时,我都会失败。例如:
新 HTML
<div class = "gridStyle2" data-bind="koGrid: GetData()"></div>
JS 使用函数
function GetData() {
$.getJSON('http://127.0.0.1:8000/home/players/', function(playerdata) {
var self = this;
this.myData = ko.observableArray(playerdata);
this.mySelectedData = ko.observableArray([]);
this.gridOptions = { data: self.myData,
columnDefs: [{ field: 'ShortName', displayName: 'Name', width: 100 },
{ field: 'CurrentVal', displayName: 'Value', width: 70 },
{ field: 'ShortClub', displayName: 'Club', width: 60 },
{ field: 'ShortPos', displayName: 'Position', width: 70 },
],
selectedItems: this.mySelectedData,
multiSelect: false,
showFilter: false,
jqueryUITheme: true,
rowHeight: 22,
displaySelectionCheckbox: false,
};
}
ko.applyBindings(GetData(), document.getElementById('newgrid'));
});
这不起作用,我也尝试过使用 var BLah = $.getJSON 等
在我对 OOP 的有限理解中,我认为调用 GetData() 会生成相同的表?谁能指出我哪里出错了?我已经尝试复制函数在 knockout.js 教程中的工作方式 - http://learn.knockoutjs.com/#/?tutorial=collections
谢谢...
【问题讨论】:
-
尝试用
ko.applyBindings(self, document.getElementById('newgrid2'))之类的东西更新第二个网格js