knockout javascript foreach binding
javascript, knockout.js
Solution
You have several problems:
You are using Knockout 1.2.1
The `foreach` binding was not added until Knockout 2.0.
You are not using an `observableArray`
You need to modify your `categories` property to be a `ko.observableArray()`, instead of just an empty array. Otherwise Knockout will not be able to observe when you `push` to it, and the `remove` method will not exist.
Your `this` binding is wrong.
When called from event handlers, `this` will be set incorrectly. You can fix this in various ways, discussed in length in the Knockout documentation, but one easy fix is to change the references to `viewModel` instead of to `this`.
To fix all these, you should upgrade to Knockout 2.0, and change your view model declaration to be
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('');
}
};
Here is a corrected JSFiddle: http://jsfiddle.net/ueNg7/19/
Problem
I'm trying to allow a user to create a casting and add an array of categories to this casting object. I was trying to use knockout's foreach binding to the array of categories and let users add new categories to the casting. I have created a jsfiddle to illustrate what I'm trying to explain here. http://jsfiddle.net/msell/ueNg7/16/ The JSON object gets built up correctly as a user modifies a casting, but I cant quite get the list of castings to display.