Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

knockout.js - Knockout observableArray not updating

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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...