gpt4 book ai didi

javascript - 过滤 observableArray

转载 作者:行者123 更新时间:2023-12-03 10:30:13 28 4
gpt4 key购买 nike

我在使用 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) }
];

View 模型:

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>

最佳答案

首先,我认为您以错误的方式使用 pos 属性。它是可观察的,因此您应该按以下方式分配它:

self.appendableData()[2].pos(2);

并在您的过滤器函数中正确检索值:

return item.pos() >= 0;

此外,我建议您使用knockout-projections库( https://github.com/SteveSanderson/knockout-projections ) - 它更有效:

self.appendableDataToView = self.appendableData.fitler(function (item) {
return item.pos >= 0;
});

关于javascript - 过滤 observableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29251006/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com