gpt4 book ai didi

javascript - KnockoutJS arrayFilter 不更新

转载 作者:行者123 更新时间:2023-11-28 08:53:31 24 4
gpt4 key购买 nike

这里是 knockout 新手。我尝试使用 ko.utils.arrayFilter 但当我使用它时它似乎没有更新。我使用与 arrayForEach 相同的方法,所以我不确定这里出了什么问题。使用 arrayFilter 时如何获取要更新的列表?

JS:

function entry(name, category) {
this.name = ko.observable(name);
this.category = ko.observable(category);
}

function entriesModel() {
this.entries = ko.observableArray([]);
this.filter = function () {
ko.utils.arrayFilter(this.entries(), function (item) {
return item.category == 'SciFi';
});
};
this.sort = function () {
this.entries.sort(function (a, b) {
return a.category < b.category ? -1 : 1;
});
};
}

$(document).ready(function () {
$.getJSON("entries.php", function (data) {
entries(data);
});
ko.applyBindings(entriesModel());
});

HTML:

<ul data-bind="foreach: entries">
<li>
<p data-bind="text: name"></p>

<p data-bind="text: category"></p>
</li>

<button data-bind="click: filter">Filter</button>
<button data-bind="click: sort">Sort</button>

JSON:

[{"id":"1","name":"Iron Man","category":"SciFi"},{"id":"2","name":"Terminator","category":"SciFi"},{"id":"3","name":"The Pianist","category":"Drama"},{"id":"4","name":"The Hangover","category":"Comedy"}]

最佳答案

不确定这是否正是您想要的,但是您的过滤函数不会执行就地过滤,因此您需要使用新的过滤数组重新分配 observableArray。比如

this.filter = function () {
this.entries(ko.utils.arrayFilter(this.entries(), function (item) {
return item.category == 'SciFi';
}));
};

请参见此处:http://jsfiddle.net/aKfUc/1/

如果您不想永久更改数组,您可能需要使用 ko.compulated observable:

http://knockoutjs.com/documentation/computedObservables.html

关于javascript - KnockoutJS arrayFilter 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18809400/

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