过滤 observableArray

Filtering observableArray

我在使用 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

过滤函数returns一个空数组:

    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;
});