我从这样的简单可观察对象创建了一个计算的可观察对象:
- this.fullDetails 是计算出来的 observable。
- this.computeFullDetails 是计算的读取函数。
- this.writeToComponents 是计算的写入函数。
当我修改与原子可观察对象对应的输入框时,计算属性会被修改,但是当我修改计算属性时,原子属性不会更新。我可以用另一种方法来完成这样的事情吗?
请看这个小提琴http://jsfiddle.net/saurabh0jha/wqpZ9/
function PersonViewModel()
{
this.firstName = ko.observable("");
this.lastName = ko.observable("");
this.phoneNos = ko.observable(0);
this.address = ko.observable("");
this.computeFullDetails = function(){
retObj = {};
retObj.firstName=ko.observable(this.firstName());
retObj.lastName=ko.observable(this.lastName());
retObj.phoneNos=ko.observable(this.phoneNos());
retObj.address=ko.observable(this.address());
return retObj;
};
this.writeToComponents = function(value){
this.firstName(value.firstName());
this.lastName(value.lastName());
this.phoneNos(value.phoneNos());
this.address(value.address());
};
this.fullDetails = ko.computed(
{
read:this.computeFullDetails,
write:this.writeToComponents,
},this);
}
var vm = new PersonViewModel();
ko.applyBindings(vm);
HTML
<html lang='en'>
<head>
<title>Hello, Knockout.js</title>
<meta charset='utf-8' />
<link rel='stylesheet' href='style.css' />
</head>
<body>
<h2>atomic</h2>
<input data-bind="value: firstName" style="display:block" />
<input data-bind="value: lastName" style="display:block"/>
<input data-bind="value: phoneNos"style="display:block" />
<input data-bind="value: address" style="display:block"/>
<h2>computed</h2>
<input data-bind="value: fullDetails().firstName" style="display:block"/>
<input data-bind="value:fullDetails().lastName" style="display:block"/>
<input data-bind="value: fullDetails().phoneNos"style="display:block" />
<input data-bind="value: fullDetails().address"style="display:block" />
<script type='text/javascript' src='knockout-2.2.0.js'></script>
<script type='text/javascript' src='2computedObservables.js'> </script>
</body>
</html>