我是knockout.js的新手,并且在构造函数中包含计算的observable时出现问题。我正在尝试将“BoughtIns”的实例添加到主视图模型中的buyIn可观察数组中。这包括数量和数量价格字段(两个可观察值),我想从中计算qxp字段。
这里有一个小提琴:http://jsfiddle.net/glassy10/racvj4c5/37/ - 小提琴按原样运行,但在html& amp;中取消注释qxp计算的observable时失败。 BoughtIn构造函数带有错误'undefined不是一个函数',它会阻止整个工作。
html:
<div class="row" data-bind="with:boughtIn">
<div><input type="text" data-bind="value:item" PlaceHolder ="Item" /></div>
<div><input type="text" data-bind="value:qty" PlaceHolder ="Qty"/></div>
<div><input type="text" data-bind="value:price" PlaceHolder ="Price"/></div>
<div><button data-bind="click:$root.addBoughtIn" >Add Item</button></div>
</div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Q x P</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach:boughtIns">
<tr>
<td data-bind="text:item"></td>
<td data-bind="text:qty"></td>
<td data-bind="text:price"></td>
<td>
<span data-bind="text:qxp"></span>
</td>
<td><a href="#" data-bind="click:$root.deleteBoughtIn">Delete</a></td>
</tr>
</tbody>
</table>
js:
var ViewModel = function() {
var self = this;
//other observables
//...
//boughtIns
self.boughtIns = ko.observableArray([]);
self.boughtIn = ko.observable(new BoughtIn());
self.addBoughtIn = function(data) {
self.boughtIns.push(data);
//reset to clear fields
self.boughtIn(new BoughtIn());
};
self.deleteBoughtIn = function(data) {
self.boughtIns.remove(data);
};
}
function BoughtIn() {
var self = this;
self.item = ko.observable(),
self.qty = ko.observable(),
self.price = ko.observable(),
self.category = ko.observable(),
//NOT WORKING ----
self.qxp = ko.pureComputed( {
read: function () { return self.qty() * self.price(); },
deferEvaluation: true
})
//----------------
}
ko.applyBindings(new ViewModel());