Yarin
Yarin

Reputation: 183929

Updating properties of an item within an observable array in Knockout

I'm trying to implement an updatable "selected item" of an observable array in Knockout, such that changes on the selected item's properties get propagated back to the list.

In the following example, my model contains a list of users in an observable array, with each user having an observable 'name' property. The model also has a selectedUser property, which references a user in the list.

I have an input control bound to the name() value of the selected user. I want to be able to change the name within the input, and see that change propagate to the list below.

JS:

var UserModel = function() {
    this.users = ko.observableArray([
                {id:1, name:ko.observable('Bob')},
                {id:2, name:ko.observable('Jane')}
            ]);
    this.selectedUser = ko.observable(this.users()[0]);
    console.log(this.users()[0].name());
}
ko.applyBindings(UserModel);

HTML:

<input type="text" data-bind="value: selectedUser().name()" value="">
<table data-bind="foreach: users()">
    <tr >
        <td data-bind="text: $data.name()"> </td>
    </tr>
</table>

FIDDLE: http://jsfiddle.net/5t5k2/5/

Upvotes: 0

Views: 1022

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276536

You're almost there.

The only problem is that you're binding the input field to an invocation of the observable and not the function itself.

When you do .name() you're invoking the observable so you get a string back. Instead, bind to the observable itself.

Change:

<input type="text" data-bind="value: selectedUser().name()" value="">

to

<input type="text" data-bind="value: selectedUser().name" value="">

( fiddle )

If you want that immediate feel, you can tell it to update on key down too and not just on the change event (that fires on tab or when you lose focus)

<input type="text" data-bind="value: selectedUser().name, valueUpdate: 'keyup'" value="">

( fiddle )

Upvotes: 6

Related Questions