0

ノックアウト 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>
4

1 に答える 1

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;
});
于 2015-03-25T09:27:18.297 に答える