访问observable数组中可观察对象的属性 - knockout.js
问题描述:
一直在学习基因敲除和获得乐趣,但我坚持的东西,我认为是如此简单:访问可观察数组内的可观察对象的属性。 我需要从activeCompMultipliers数组内的activeCompMultiplier对象中获取“multiplierValue”。访问observable数组中可观察对象的属性 - knockout.js
这里是我的所有相关代码:
首先,创建并推入数组对象。这是我想谈:
var activeCompMultiplier = function (multiplierValue) {
this.multiplierValue = ko.observable(multiplierValue);
}
这是包含观察对象的观察到的数组:
self.activeCompMultipliers = ko.observableArray();
下面是创建一个新的对象,并将其推入行array:
self.activeCompMultipliers.push(new activeCompMultiplier(1));
最后,当输入字段触发'change'事件时,这就是所谓的。我使用的是警报()来调试问题:
self.inputChanged = function (rowIndex) {
alert("Multiplier is: " + self.activeCompMultipliers()[rowIndex].multiplierValue() + "\n At index: " + rowIndex);
}
Annnnd这里我相关的HTML:
<tbody data-bind="foreach: activeParts">
<tr>
<td class="ShoppingEntry" data-bind="text: $data"></td>
<td class="Textbox" >
<input type="number" class="TextBoxInput"
data-bind="value: $root.activeCompMultipliers()[$index()],
event: { change: inputChanged.bind(self, $index())},
attr: {id: 'Textbox' + $index()}" /></td>
<td class="DeleteCell">
<input type="image" src="/Assets/list_remove.png" class="DeleteButtonInput" data-bind="click: deactivatePart"/></td>
</tr>
</tbody>
我认为它是一个语法问题,因为JS是不是我的最强的语言,但我使用圆括号进行三重检查以取消包装KO可观察量,所以也许这是一个范围问题?
我所有的JS是一个function ViewModel() {...}
函数内,即然后通过
绑定为一个长期的潜伏者,我感谢所有帮助。 :)
答
3点:
你不是遍历
activeCompMultipliers
但使用的activeParts
的$index()
来访问它,这是否意味着这两个阵列具有相同的尺寸和链接?-
如果
index()
是正确的,值绑定到一个activeCompMultiplier
例如,它应该被绑定到其multiplierValue
领域:<input type="number" class="TextBoxInput" data-bind="value: $root.activeCompMultipliers()[$index()].multiplierValue,
-
变化事件势必
inputChanged
你改变了它的范围,self
,但是那个时候self
是什么?它的功能已经引用了正确的self
。应该是:event: { change: function() { inputChanged($index()); } }
或至少:
event: { change: inputChanged.bind(null, $index()) }
感谢@manji。您的观点: 1)是这些阵列是相同的大小和链接 2)这是正确的,不知道为什么我错过了...但添加。multiplierValue导致我的HTML变得扭曲 3)分号结束之前是否需要分号?这似乎会导致问题。 – 2014-09-22 05:30:14
我想我会尝试不使用可观察的路线,因为它可能会矫枉过正。我只需抓住为计算调用inputChanged时传入的值。 – 2014-09-22 05:54:28
是的,这是一个错字,带'bind'的例子不需要分号。 – manji 2014-09-22 09:51:07