我在使用 knockout.js 过滤可观察数组时遇到问题
我的js:
包含数据的数组
var docListData = [
{ name: "Article Name 1", info: "Authors, name of edition, publishing year,(moreinfo?)", checked:ko.observable(false) },
{ name: "Article Name 2", info: "Authors, name of edition, publishing year,(moreinfo?)", checked:ko.observable(false) },
{ name: "Article Name 3", info: "Authors, name of edition, publishing year,(moreinfo?)", checked:ko.observable(false) }
];
视图模型:
var viewModel = function() {
var self = this;
用数据填充可观察数组
self.docList = ko.observableArray(
ko.utils.arrayMap(docListData, function (item) {
return item;
})
);
self.appendableData = ko.observableArray([]);
在可观察数组中创建附加参数
for (var i=0; i < self.docList().length; i++){
self.docList()[i].type = "document";
self.docList()[i].id = i;
self.docList()[i].pos = ko.observable(-1);
// self.docList()[i].pos = -1;
self.appendableData().push(self.docList()[i]);
};
更改我的可观察数组中的附加值并将更改记录到控制台的函数
toggleChecked = function (){
this.checked(!this.checked());
if (this.checked() === true){
this.pos = self.position; // changes value, but doesn't affect target array
self.appendableData()[this.id].pos = self.position; //second try, same result
self.position++;
console.log("this.pos",this.pos);
console.log("this id: ", this.id);
} else if(this.checked() === false) {
this.pos = self.position;
self.position--;
console.log("this.pos",this.pos);
console.log('nope');
};
console.log("position for next: ",self.position);
console.log(self.appendableData());
console.log(self.appendableDataToView());
};
手动更改会影响目标阵列
self.appendableData()[2].pos =2; // this affects target array
过滤函数返回一个空数组:
self.appendableDataToView = ko.computed(function () {
return ko.utils.arrayFilter(self.appendableData(), function (item) {
return item.pos >= 0;
});
});
我的html代码:
<div class="list-wrapper">
<ul class="unstyled" data-bind="if: docList().length > 0">
<li data-bind="foreach: docList">
<label class="checkbox" data-bind="click: toggleChecked">
<p data-bind="text: name"></p>
<span data-bind="text: info"></span>
</label>
</li>
</ul>
</div>