2
votes

I have an observableArray filled with observables which I want to bind against input fields, like in this fiddle:

<ul data-bind="foreach: elements">
    <li>
        <input type="text" data-bind="value: $data"/>
    </li>
</ul>

However, the observables within the array are being unwrapped, so the observable's value at that time is bound to the input's value, instead of the observable itself.

Is it possible to bind the observable itself, instead of binding against the value?

In a different question, RP Niemeyer suggested to wrap the observable within an object. This is my current solution, but I don't like to redundantly wrap the observable and would rather bind it directly.

1
The data by the time it reaches the value binding on your input is already unwrapped (just the value of the observable), so writes are not able to make it back to your observable. You would still need to wrap it in an object to make this work currently. - RP Niemeyer
That's what I was afraid of. You say that this needs to be done currently, does that indicate that it is something you are working on? - Jesse van Assen
We have an issue and some work on supporting observable view models here: github.com/SteveSanderson/knockout/issues/485. However, inside of a foreach loop if the data has already been unwrapped, then there is no way to get back to the observable. I could see maybe adding an option to not unwrap at some point. - RP Niemeyer
If you do need to this (can't remap your structure) and don't mind the syntax, then I don't see a problem with doing want the answer by Sujesh Arukil suggests. - RP Niemeyer
@RPNiemeyer This was actually easier to implement than I thought. I've created a pull request. - Jesse van Assen

1 Answers

2
votes

There is no indirect way of doing it in your case. But, if you want, you can use $parent.elements()[$index()] to do this.

<input type="text" data-bind="value: $parent.elements()[$index()], click: function() { console.log($data); }"/>

Here is your updated fiddle. http://jsfiddle.net/sujesharukil/qRXua/1/