我是使用 knockoutjs 的新手,在使用 .computed() 时遇到了这个问题
这是我的 HTML 代码:
<table style="float:left;padding-right:250px" cellspacing="3">
<tr>
<td>Product Name</td>
<td>Price</td>
<td>Stocks</td>
</tr>
<tbody data-bind="foreach: Products">
<tr>
<td><a href="#" data-bind="text: Name, click:$root.addProduct, value: Name"></a></td>
<td><input data-bind="value: Price" size="3"/></td>
<td data-bind="text:Stocks"></td>
</tr>
</tbody>
</table>
<table style="float:left">
<tr>
<td>SKU</td>
<td>Product Name</td>
<td>Price</td>
<td>Qty</td>
<td>Sub</td>
</tr>
<tbody data-bind="foreach: Cart">
<tr>
<td data-bind="text: SKU"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: Quantity"></td>
<td data-bind="text: SubTotal()"></td>
<td><a href="#" data-bind="click: $root.removeProduct">Remove</a></td>
</tr>
</tbody>
</p>
这是我的脚本代码:
var Product = function(data) {
var self = this;
self.SKU = ko.observable(data.SKU);
self.Name = ko.observable(data.Name);
self.Price = ko.observable(data.Price);
self.Stocks = ko.observable(data.Stocks);
self.Quantity = ko.observable(data.Quantity);
self.SubTotal = ko.computed(function() {
return self.Quantity() * self.Price();
});
};
function ProductViewModel() {
var self = this;
var items = [{
Name: "Crystalys",
SKU: "00001",
Price: 500,
Stocks: 12,
Quantity: 0},
{
Name: "Aghanim's Scepter",
SKU: "00002",
Price: 4200,
Stocks: 5,
Quantity: 0},
{
Name: "Vladmir's Offering",
SKU: "00003",
Price: 500,
Stocks: 10,
Quantity: 0},
{
Name: "Pwer Threads",
SKU: "00004",
Price: 1450,
Stocks: 20,
Quantity: 0},
{
Name: "Satanic",
SKU: "00005",
Price: 6150,
Stocks: 5,
Quantity: 0},
{
Name: "The Butterfly",
SKU: "00006",
Price: 6000,
Stocks: 4,
Quantity: 0},
{
Name: "Divine Rapier",
SKU: "00007",
Price: 6200,
Stocks: 1,
Quantity: 0},
{
Name: "Iron Wood Branch",
SKU: "00008",
Price: 53,
Stocks: 100,
Quantity: 0}];
self.Products = ko.observableArray(items);
self.Cart = ko.observableArray();
// Operations
self.addProduct = function(Product) {
self.Cart.push({
Name: Product.Name,
Price: Product.Price,
Quantity: 1,
SKU: Product.SKU
});
}
self.removeProduct = function(Product) {
self.Cart.remove(Product)
}
}
ko.applyBindings(new ProductViewModel());
我真的不知道似乎是什么错误。请帮忙。先感谢您。