Reputation: 3923
I'm following along with the Succinctly series on Knockout.js.
I've gone through their code to the T, yet I'm getting an unusual error, which doesn't seem to have an obvious answer.
Here's my 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);
Here's my view:
<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>
I'd just like to note that KO is successfully displaying all the data (Joe Jesse and the array of observable products). However, when I click on the button to trigger addProduct()
, I receive a "undefined is not a function".
The error is explicitly referring to addProduct:
this.shoppingCart.push(new Product("Moar Beer", 12.99));
What's going on here?
Upvotes: 1
Views: 549
Reputation: 126042
shoppingCart
needs to be an observableArray
:
this.shoppingCart = ko.observableArray([
new Product("Beer", 12.99),
new Product("Wine", 29.99),
new Product("Chips", 1.99)
]);
// 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.observableArray([
new Product("Beer", 12.99),
new Product("Wine", 29.99),
new Product("Chips", 1.99)
]);
this.addProduct = function() {
console.log(this);
this.shoppingCart.push(new Product("Moar Beer", 12.99));
};
};
var vm = new PersonViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<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>
Upvotes: 1