问题
I have an observableArray that won't update in the HTML even though I can log it to the console and see it change. I wish jsfiddle had a console so I could show that part.
In the example I posted I have a list of people then I search across that list and try to add the results to a new observableArray. The search result observableArray never updates in the HTML.
Here is my Jsfiddle: http://jsfiddle.net/hMmgV/1/
Here is my code:
function AppViewModel() {
var self = this;
self.people = ko.observableArray([{
fName: "Thomas",
lName: "Edison"
}, {
fName: "Sally",
lName: "Salputrio"
}, {
fName: "Edward",
lName: "Sparkleshine"
}, {
fName: "Jacob",
lName: "Wolfsson"
}]);
self.searchResult = ko.observableArray([]);
self.searchFieldKo = ko.observable("");
self.submitSearch = function () {
if (self.searchFieldKo() != "") {
self.searchResult().length = 0;
$.each(self.people(), function (pKey, pObj) {
$.each(pObj, function (pProp, pValue) {
if (pValue.toString().toLowerCase().indexOf(self.searchFieldKo().toLowerCase()) >= 0) {
self.searchResult().push(self.people()[pKey]);
console.log(self.searchResult());
}
})
})
} else {
alert("Please type something.");
}
}
}
ko.applyBindings(new AppViewModel());
回答1:
You have an unnecessary set of parenthesis in
self.searchResult().push(self.people()[pKey]);
it should be
self.searchResult.push(self.people()[pKey]);
Demo JSFiddle.
Because when you write self.searchResult() you are accessing the underlaying array in the observable. And when you push into that array KO won't be notified about the changes so you need to use the push method on the observableArray itself.
By the way Knockout has a great set of useful array helpers which could simplify your filtering logic.
来源:https://stackoverflow.com/questions/16068125/knockout-observablearray-not-updating