user2834172
user2834172

Reputation: 891

knockout array binding not working

monkeyStuff does what i want, it updates the span content if i write in the input field. But why doesn't it work with the voteStuff?

See it in Action: Fiddle

<body>
    <div id="monkeyStuff">
        <input type="text" data-bind="value:monkey" />
        <span data-bind="text:monkey"></span>
    </div>
    <hr>
    <div id="voteStuff">
        <div data-bind="text: test"></div>
        <ul data-bind="foreach: voters">
          <li>
            <input type="text" data-bind="value:name" />
            <span data-bind="text:name"></span>
          </li>
        </ul>
    </div>

    <script>        
        var vm = {
            monkey: ko.observable()
        };
        vm.monkey("Quak");
        ko.applyBindings(vm, document.getElementById('monkeyStuff'));

        var model = {
            test: 'Test address text',
            voters: ko.observableArray([
                { name: 'First Voter' },
                { name: 'Second Voter' }
            ])
        };

        ko.applyBindings(model, document.getElementById('voteStuff') );

    </script>
</body>

EDIT: OK it works like this:

  voters: ko.observableArray([
        { name: ko.observable('First Voter') },
        { name: ko.observable('Second Voter') }
    ])

But is there a way to do it automatic for each property in the voters array?

Upvotes: 0

Views: 561

Answers (1)

PaulDapolito
PaulDapolito

Reputation: 824

You need to make the name property of the elements in your voters ko.observableArray also observable, which would thus allow you to alter these properties with the bindings you have implemented:

    voters: ko.observableArray([
        { name: ko.observable('First Voter') },
        { name: ko.observable('Second Voter') }
    ])

Working example: http://jsfiddle.net/he2zoa3d/2/

Upvotes: 2

Related Questions