JSFiddle - React, Tailwind, and code Playground
by Castrolol
HTML
<div data-bind="with: item">
Nome: <input data-bind="value: nome" />
<br/>
Idade: <input data-bind="value: idade" />
<br/>
outro: <input data-bind="value: outro().prop" />
<br/>
outro: <input data-bind="value: outro().maisUm().prop" />
<button data-bind="click: $root.save">salvar</button>
<button data-bind="click: $root.clear">limpar</button>
</div>
<ul data-bind="foreach: itens ">
<li data-bind="with: $data " >
<span data-bind="text: nome"></span>
<span data-bind="text: idade"></span>
<span data-bind="text: outro().prop()"></span>
<span data-bind="text: outro().maisUm().prop()"></span>
<button data-bind="click: $root.edit">edit</button>
</li>
</ul>
JavaScript
(function (w) {
var mapper = function () { }
var publico = mapper.prototype;
function corrigir(a,nonFirst) {
if (typeof a != "function" && !nonFirst) {
a = ko.observable(a);
}
return a;
}
function copy(a, b, nonFirst) {
a = corrigir(a, nonFirst);
b = corrigir(b, nonFirst);
for (var i in a()) {
if (typeof a()[i] == "function" && a()[i].subscribe) {
if (typeof b()[i] == "function" && b()[i].subscribe) {
if (typeof a()[i]() == "object") {
copy(a()[i], b()[i]);
} else {
b()[i](a()[i]());
}
}
}
}
}
function clone(obj) {
if (typeof obj == "function" && obj.subscribe) {
var objChild = clone(obj());
return ko.observable(objChild);
}
if (typeof obj != "object" && typeof obj != "array") return obj;
if (obj == null) return null;
if (typeof obj == "array" || (obj.length >= 0 && obj.push && obj.pop)) {
var retorno = [];
for (var i = 0; i < obj.length; i++) {
retorno.push(clone(obj[i]));
}
return retorno;
}
var retorno = {};
for (var i in obj) {
retorno[i] = clone(obj[i]);
}
return retorno;
}
publico.copyTo = function (to, from) {
copy(from, to);
}
publico.copyFrom = function (from,to) {
copy(from, to);
}
publico.clone = function (obj) {
return clone(obj);
}
window.Mapper = new mapper();
})(window);
var ns = {};
ns.outro = function(n){
this.prop= ko.observable(n);
this.maisUm = ko.observable( new ns.maisUm("outro") );
}
ns.maisUm = function(n){
this.prop= ko.observable(n);
}
var pessoa = function(n,i){
this.nome = ko.observable(n);
this.idade = ko.observable(i);;
this.outro = ko.observable( new ns.outro("oi") );
return this;
}
var vm = function()
{
var self = this;
self.itens = ko.observableArray([]);
self.item = ko.observable(new pessoa ());
var updating = null;
var update = function(){
Mapper.copyTo(updating, self.item);
clear();
}
self. edit = function(item){
console.log(item);
...