You're facing some issues:
Your Knockout version is outdated at 1.2.1
The foreach
binding was introduced in Knockout 2.0.
You're not utilizing an observableArray
You need to transform your categories
property into a ko.observableArray()
, rather than just an empty array. Without this adjustment, Knockout won't be able to monitor changes via push
, and the remove
method will not function.
Your use of this
binding is incorrect.
When used in event handlers, the context of this
may be incorrect. There are multiple ways to address this, as detailed in the Knockout documentation, but one simple fix is to refer to viewModel
instead of this
.
To resolve these issues, consider upgrading to Knockout 2.0 and adjust your view model setup like so:
var viewModel = {
name: ko.observable(''),
description: ko.observable(''),
categories: ko.observableArray(),
categoryToAdd: ko.observable(''),
removeCategory: function(category) {
viewModel.categories.remove(category);
},
addCategory: function() {
viewModel.categories.push(new Category(viewModel.categoryToAdd()));
viewModel.categoryToAdd('');
}
};
Check out the corrected JSFiddle here: http://jsfiddle.net/ueNg7/19/