简体   繁体   中英

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?

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/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM