简体   繁体   English

如何在ko.observableArray中更新从零开始的索引数组

[英]How to update a zero-based index array in ko.observableArray

I'm a new programmer for knockout. 我是淘汰赛的新程序员。 Here's a question about ko.observableArray while practicing. 这是练习时有关ko.observableArray的问题。 I give an zero-based index array for initial data that will show with JSON while clicking button. 我为初始数据提供了一个从零开始的索引数组,在单击按钮时将以JSON显示。 But when I try to update any value from input field but I cannot get the new JSON after clicking button. 但是,当我尝试更新输入字段中的任何值,但单击按钮后无法获取新的JSON时。

And I think the problem is that there's no index in my array.How can I get the new JSON after clicking 我认为问题是我的数组中没有索引,单击后如何获取新的JSON

 function ViewModel(inputs){ this.inputs = ko.observableArray(inputs); this.getData = function(){ this.jsonData(ko.toJSON(this.inputs)); }; this.jsonData = ko.observable(''); }; var initialData = [ 'Jan', 'Feb', 'Mar', 'etc' ]; var viewModel = new ViewModel(initialData); ko.applyBindings(viewModel); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script> <ul data-bind="foreach: inputs"> <li> The current item is: <input type='text' data-bind="value: $data"></b> </li> </ul> <textarea rows='5' cols='60' data-bind='value: jsonData'> </textarea> <button data-bind='click: getData'>get Data</button> 

I thing due to $index you can't get this updated JSON 我的东西由于$ index您无法获得此更新的JSON

if you add key value pair in "initialData" you will get updated JSON data 如果在“ initialData”中添加键值对,则将获取更新的JSON数据

Here blow working code : 这里吹工作代码:

function ViewModel(inputs) {
    this.inputs = ko.observableArray(inputs);

    this.getData = function () {
        this.jsonData(ko.toJSON(this.inputs));
    };

    this.jsonData = ko.observable('');
};


var initialData = [{ name: 'Jan' }, { name: 'Feb' }, { name: 'Mar' }, { name: 'etc' }];

var viewModel = new ViewModel(initialData);

ko.applyBindings(viewModel);


<ul data-bind="foreach: inputs">
    <li>
        The current item is: <input type='text' data-bind="value: name"><br />
    </li>
</ul>
<textarea rows='5' cols='60' data-bind='value: jsonData'> </textarea>
<button data-bind='click: getData'>get Data</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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