JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<p data-bind="text: 'Edit Index:' + editIndex()"></p>
<button data-bind="click: increase">Increase edit index</button>
<button data-bind="click: add">Add Address</button>
<button data-bind="click: edit">Edit Address</button>
<button data-bind="click: function(o, e){method = !method}">Switch edit method</button>
<ul data-bind="foreach: addresses">
<!-- ko template: {name: 'ListItem', data: {address: $data, page: $index}} --><!-- /ko -->
</ul>
<script type="text/html" id="ListItem">
<li>
<p data-bind="text: page() + ' ' + address.title"></p>
<div>
<p data-bind="text: address.num"></p>
<p data-bind="text: address.detail.city.town + ' / ' + address.detail.city.district.name"></p>
</div>
</li>
</script>
JavaScript
var randomAddress = function(){
this.num = Math.random();
this.title = Math.random().toString(36).slice(-5);
this.detail = {
city : {
town: Math.random().toString(36).slice(-5),
district: {
name: Math.random().toString(36).slice(-5)
}
}
};
};
var ViewModel = function(){
this.method = true;
this.editIndex = ko.observable(0);
this.addresses = ko.observableArray();
};
ViewModel.prototype.increase= function() {
this.editIndex(this.editIndex() + 1);
};
ViewModel.prototype.add = function(){
this.addresses.push(new randomAddress());
};
ViewModel.prototype.edit = function(){
if(this.method) this.editMethod1();
else this.editMethod2();
};
ViewModel.prototype.editMethod1 = function(){
var tmp_addresses = JSON.parse(JSON.stringify(this.addresses()));
tmp_addresses[this.editIndex()].title = Math.random().toString(36).slice(-5);
this.addresses(tmp_addresses);
};
ViewModel.prototype.editMethod2 = function(){
var tmp_addresses = this.addresses();
tmp_addresses[this.editIndex()] = new randomAddress();
this.addresses(tmp_addresses);
};
ko.applyBindings(new ViewModel());