A Knockout newbie here. I've tried to use ko.utils.arrayFilter but it doesn't seem to update when I use it. I'm using the same method I used with arrayForEach so I'm not sure what's wrong here. How can I get this the list to update when using 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"}]
ko.utils.arrayFilter
doesn't filter the array in place. It returns a new array with the filtered items, and leaves the original array as is.
An example of how to use ko.utils.arrayFilter
is here: http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html
Not sure if this is exactly what you want, but your filter function won't do an in-place filter, so you need to reassign the observableArray with the new filtered array. Such as
this.filter = function () {
this.entries(ko.utils.arrayFilter(this.entries(), function (item) {
return item.category == 'SciFi';
}));
};
See here: http://jsfiddle.net/aKfUc/1/
If you don't want to permanently change the array, you may want to use a ko.computed observable:
http://knockoutjs.com/documentation/computedObservables.html
data-bind="value: currentFilter, valueUpdate: 'afterkeydown'"
将解决您的问题
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.