正如标题所说,我正在尝试将一个可观察对象的值添加到另一个可观察对象。我得到了奇怪的结果,我想知道我是否以正确的方式做这件事。
底部的小提琴
HTML:
<div id="wrapper">
<ul class="empiriHelp" data-bind="foreach: empiriHelp"><li data-bind="text: title"></li></ul>
<ul class="empiricount" data-bind="foreach: $data.empiriLines">
<li data-bind='event: {mouseover: $root.empiriMouseOver, mouseleave: $root.empiriMouseLeave}'>
<input class="empiri_amount" data-bind="value: $data.amount"/>
<select data-bind="options: $root.measurements, value: $data.unit = $root.selectedUnit"></select>
<input class="empiri_ingredient" type="text" data-bind="value: $data.ingredient, returnKey: $root.empiriAddLine.bind($data, $index())" />
<div class="empiri_fader">
<div class="empiri_add" data-bind="click: $root.empiriAddLine.bind($data, $index())"></div>
<div class="empiri_delete" data-bind="click: $root.empiriRemoveLine.bind($data, $index())"></div>
</div>
</li>
</ul>
</ul>
</div>
Javascript:
$(document).ready(function()
{
var viewModel = function(){
var self = this;
self.selectedUnit = ko.observable();
self.selectedUnit.subscribe(function(value) {
console.log(value);
});
self.measurements = ko.observableArray([
ko.observable('Kg'),
ko.observable('g'),
ko.observable('L'),
ko.observable('dl'),
ko.observable('cl'),
ko.observable('tbps'),
ko.observable('tsp'),
ko.observable('cl')
]);
self.empiriHelp = [{title: "amount"}, {title: "unit"}, {title: "ingredient"}];
self.empiriLines = ko.observableArray([{ amount: ko.observable(''), unit: ko.observable(self.measurements[0]), ingredient: ko.observable('') }]);
self.empiriAddLine = function(index){
self.empiriLines.splice(index+1,0,{ amount: ko.observable(''), unit: ko.observable(self.measurements[0]), ingredient: ko.observable('') });
}
self.empiriRemoveLine = function(index){
if(self.empiriLines().length!=1){
self.empiriLines.splice(index,1);
}
}
self.empiriMouseOver = function(data, event){
$(event.currentTarget).find(".empiri_fader").stop(true, true).fadeIn(200);
}
self.empiriMouseLeave = function(data, event){
$(event.currentTarget).find(".empiri_fader").stop(true, true).fadeOut(200);
}
}
ko.applyBindings(new viewModel);
The issue is that when the select value changes, it changes value on ALL the empirilines which i don't understand... shouldn't $data be context sensitive and only refer to the current loop item from the foreach? 我的猜测是我以错误的方式绑定了 observables。我一直在努力反对这个问题太久了,我的大脑一片混乱。
我今天不能动脑筋,我有哑巴- halp!
这是小提琴:http: //jsfiddle.net/Y9Caw/