JSFiddle - React, Tailwind, and code Playground
by origineil
HTML
<script src="https://rawgit.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<script type="text/html" id="template">
<hr/>
<div data-bind="foreach: entarea">
<span data-bind="text: displayName"></span>
<br/>
</div>
<span data-bind="text: ko.toJSON(selectedArea)"></span>
</script>
<div data-bind="foreach: options">
<input type='radio' data-bind='attr:{value: ko.toJSON(data)}, checked: $root.selected'></input>
<span data-bind='text: $data.name'></span>
<br/>
</div>
<div data-bind='with: selected'>
<div id='default' data-bind="template: { name: 'template', data: JSON.parse($data) }"></div>
</div>
JavaScript
function Condition(initIndex) {
var data = [{
displayName: "Client",
sqlAreaId: 1
}, {
displayName: "Order",
sqlAreaId: 2
}];
var self = this;
self.entarea = ko.observableArray(data)
self.selectedArea = ko.observable(initIndex !== undefined ? data[initIndex] : data[1])
}
var init = {
selectedArea: {
displayName: "Client",
sqlAreaId: 1
}
};
function defaultImpl(){
return {name: "Default - Basic binding to a new Condition()",
data: new Condition()}
}
function behaviorImpl1(){
return {
name: "Overrides entArea[1] during ko.mapping due to shared object reference",
data: ko.mapping.fromJS(init, {}, new Condition())}
}
function behaviorImpl2(){
return {
name: "Overrides entArea[0] during ko.mapping due to shared object reference",
data: ko.mapping.fromJS({
selectedArea: {
displayName: "Order",
sqlAreaId: 2
}
}, {}, new Condition(0))}
}
function potentialWorkaroundImpl(){
return {
name: "Override prevented by using 'update' callback",
data: ko.mapping.fromJS( init, {
'selectedArea': {
update: function (options) {
return options.data;
}
}
}, new Condition())
}
}
function differentObjectImpl(){
self = this;
self.name="entArea and selectedArea do not contain the same Object Reference";
var condition = new Condition();
condition.selectedArea( {
displayName: "Order",
sqlAreaId: 2
});
self.data = ko.mapping.fromJS(init, {}, condition);
return self;
}
var vm = {
options: ko.observableArray([defaultImpl(),
behaviorImpl1(),
behaviorImpl2(),
...