正如标题所说,我正在尝试将一个值从一个observable添加到另一个observable。 我得到了奇怪的结果,我想知道我是否采用了正确的方法。
FIDDLE at the BOTTOM
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);
问题是,当选择值发生变化时,它会更改所有我不理解的empirilines的值...不应该$ data是上下文敏感的,只引用foreach中的当前循环项?我的猜测是我以错误的方式约束了这些观察者。我一直在抨击这个问题太长时间了,我的大脑很难糊涂。
我今天无法大脑,我有愚蠢的停止!
这是小提琴: http://jsfiddle.net/Y9Caw/
答案 0 :(得分:1)
实际上,只需删除= $root.selectedUnit
就可以来做你想做的事了:
value: $data.unit = $root.selectedUnit