简体   繁体   中英

How to properly bind text box value back to model in a observable array?

I have a model that has an observable array, I can display the data in a text box, but I can't figure out how to bind it back to the original array.

Here is the working sample I have.

<ul data-bind='foreach: frameworks'>
    <li>
        <button class='btn' value='pick me'             
            data-bind='text: name, click: $parent.selectFramework'>            
        </button>
    </li>
</ul>
<input type='text' data-bind='value: selectedFramework().name' />
<pre data-bind='text: ko.toJSON($root.selectedFramework, null, 4)'>
</pre>



var Framework = {
    name: ''
};

var App = new function () {
        var self = this;
        self.frameworks = ko.observableArray();
        self.selectFramework = function (item) {
            self.selectedFramework(item);
        };
        self.selectedFramework = ko.observable(Framework);
    };

App.frameworks([{name: 'foo'}, {name: 'bar'}]);

ko.applyBindings(App);

The value is only stored in your selectedFramework observable, so you would be able to access it via App.selectedFramework(). The observable doesn't take any variable and make it observable, it will store whatever value you pass it internally. If you want to update the external Framework variable, you would do that in your selectFramework function.

self.selectFramework = function (item) {
        self.selectedFramework(item);
        Framework = item;
    };

You are almost there. You need to make the 'name' properties on each framework observable. I have updated your JsFiddle here

App.frameworks([{
    name: ko.observable('foo')
}, {
    name: ko.observable('bar')
}]);

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