user2221085
user2221085

Reputation: 1

knockout not updating values in view

I have the following markup:

<ul data-bind="foreach: nameList">
    <li data-bind="text: $data"></li>
</ul>
<button data-bind="click: addname">add name</button>
Total names: <span data-bind="text: nameList().length"></span>

My viewmodel looks like this:

var viewmodel = {
    nameList: ko.observableArray(["Brian"]),
    number: ko.observable(100),
    addname: function(){
        alert(this.nameList().length);
        this.nameList().push("name");
        alert(this.nameList().length);
    }
};

ko.applyBindings(viewmodel);

Whenver the addname method is executed, alert updates the nameList array, but the markup doesn't reflect these changes. So what's wrong with it?

Upvotes: 0

Views: 84

Answers (1)

Piet van Dongen
Piet van Dongen

Reputation: 1639

Got it! You need to change:

this.nameList().push("name");

To this:

this.nameList.push("name");

(Because nameList is an array, not a method)

Demo: http://jsfiddle.net/G464V/

Upvotes: 2

Related Questions