【发布时间】:2014-11-27 09:31:03
【问题描述】:
我正在关注 Knockout.js 上的 Succinctly 系列。
我已经检查了他们的代码到 T,但我遇到了一个不寻常的错误,似乎没有明显的答案。
这是我的 JS:
// create view models for Knockout
function Product(name, price) {
this.name = ko.observable(name);
this.price = ko.observable(price);
};
function PersonViewModel() {
this.firstName = ko.observable("Joe");
this.lastName = ko.observable("Jesse");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
this.shoppingCart = ko.observable([
new Product("Beer", 12.99),
new Product("Wine", 29.99),
new Product("Chips", 1.99)
]);
this.addProduct = function() {
this.shoppingCart.push(new Product("Moar Beer", 12.99));
};
};
var vm = new PersonViewModel();
ko.applyBindings(vm);
这是我的看法:
<p data-bind="text: fullName"></p>
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody data-bind="foreach: shoppingCart">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: price"></td>
</tr>
</tbody>
</table>
<div class='ui button' data-bind="click: addProduct">
Moar Beer
</div>
我只想指出,KO 已成功显示所有数据(Joe Jesse 和可观察产品数组)。但是,当我点击按钮触发addProduct() 时,我收到“未定义不是函数”。
错误是明确引用 addProduct:
this.shoppingCart.push(new Product("Moar Beer", 12.99));
这是怎么回事?
【问题讨论】:
-
如果你想将项目推送到 observable,如果 shoppingCart 只是一个 observable,你需要像这样使用 this.shoppingCart().push(new Product("Moar Beer", 12.99 ));
标签: knockout.js