在下面的代码中我试图在self.data中添加一个对象,这是一个ObservableArray,但在迭代之后,self.data中有0个元素。你能帮我解决一下我失踪的事吗?
感谢您提前付出的努力
var self = this;
self.data = ko.observableArray();
// self.data = [{ icon: 'http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png', item_name: '11:24 am', item_desc: '24/01', item_rate: 'Edited Online Form and got "Digital Signature" by Samantha Brown' },
// { icon: 'http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png', item_name: '11:24 am', item_desc: '24/01', item_rate: 'Edited Online Form and got "Digital Signature" by Samantha Brown' },
// { icon: 'http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png', item_name: '11:24 am', item_desc: '24/01', item_rate: 'Edited Online Form and got "Digital Signature" by Samantha Brown' },
// { icon: 'http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png', item_name: '11:24 am', item_desc: '24/01', item_rate: 'Edited Online Form and got "Digital Signature" by Samantha Brown' },
// { icon: 'http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png', item_name: '11:24 am', item_desc: '24/01', item_rate: 'Edited Online Form and got "Digital Signature" by Samantha Brown' }
// ];
function DashboardViewModel() {
this.nowrap = ko.observable(false);
$.getJSON("http://127.0.0.1:3000/items/").
then(function (items) {
console.log(">> " + items[0].item_desc);
$.each(items, function () {
var item = {
icon: 'http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png',
item_name: this.item_name,
item_desc: this.item_desc,
item_rate: this.item_rate
};
self.data.push(item);
console.log(self.data.length);
});
});
self.dataSource = new oj.ArrayTableDataSource(self.data, { idAttribute: "item_name" });
}
以下是HTML代码,
<div class="oj-flex oj-flex-items-pad">
<div class="oj-sm-4 oj-md-6 oj-lg-12 oj-flex-item fontStyle" style="text-align: start;">
<ul id="listview" aria-label="list with context menu" contextmenu="myMenu" data-bind="ojComponent: {component: 'ojListView', data: dataSource, item: {template: 'server_template'}, selectionMode: 'single'}">
</ul>
</div>
</div>
答案 0 :(得分:0)
试试这个:
console.log(self.data().length);
添加括号。
ko.observableArray
没有length
属性,因此您必须先打开内部数组。
最后一行也是self.data()
而不是self.data
。如果oj.ArrayTableDataSource
需要标准数组而不是ko.observableArray
。
答案 1 :(得分:0)
视图模型:
var self = this;
self.data = ko.observableArray();
$.get("url").done(function(result) {
self.data(result);
});
return self;
HTML:
<div data-bind="foreach: data">
<div>
<img src="http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-11/512/add-item-icon.png" alt="" />
</div>
<div data-bind="text: item_name"></div>
</div>