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.
/
The JSON object gets built up correctly as a user modifies a casting, but I cant quite get the list of castings to display.
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/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.
Share Improve this question edited Apr 24, 2012 at 6:02 Cody Hatch 8,9376 gold badges31 silver badges36 bronze badges asked Apr 11, 2012 at 4:06 mattmatt 1031 silver badge7 bronze badges2 Answers
Reset to default 10You 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/ueNg7/19/
You need to use ko.observableArray for you array otherwise Knockout wont know when you change your array and wont update, also you should use a template instead, read here http://knockoutjs./documentation/template-binding.html#note_2_using_the_foreach_option_with_a_named_template
var viewModel = {
name: ko.observable(''),
description: ko.observable(''),
categories: ko.observableArray([]),
categoryToAdd: ko.observable(''),
removeCategory: function(category) {
this.categories.remove(category);
},
addCategory: function() {
this.categories.push(new Category(this.categoryToAdd()));
this.categoryToAdd('');
}
};