我在使用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>
答案 0 :(得分:1)
首先,我认为您以错误的方式使用pos
属性。它是可观察的,所以你应该按照以下方式分配它:
self.appendableData()[2].pos(2);
并在您的过滤器函数中正确检索值:
return item.pos() >= 0;
此外,我建议你使用淘汰赛投影库(https://github.com/SteveSanderson/knockout-projections) - 它效率更高:
self.appendableDataToView = self.appendableData.fitler(function (item) {
return item.pos >= 0;
});