Craig
Craig

Reputation: 18704

Adding objects to an array and then showing in a table

I'm trying to learn Knockout. In my little project, I want to type in a firstname, a surname, and add it to an array of 'people' objects - and then show the list in a table using a foreach.

https://jsfiddle.net/2pf07vdh/

I'm new to fiddler too, so don't think the knockout is loading (The little checkbox should hide and show stuff, but it's not), but with this, in my editor, I get an error:

knockout-3.4.1.js:72 Uncaught ReferenceError: Unable to process binding "foreach: function (){return People }"(…)

That's when the screen loads.

And then when I try add an object to my array, I get this:

knockout-3.4.1.js:14 Uncaught TypeError: Cannot read property 'length' of undefined(…)

Can anyone see why I'm struggling so much? I think maybe I can't declare the 'Person' object like this?

Upvotes: 0

Views: 64

Answers (1)

user3297291
user3297291

Reputation: 23382

In this line:

self.People = ko.observableArray([Person]);

you're creating an observable array with a reference to a class/function in it. If you want to create an actual person, you'll have to use the new keyword. Note that FirstName will still be undefined.

self.People = ko.observableArray([]); // Opt 1. Initialize as empty list
self.People = ko.observableArray([new Person()]); // Opt 2. With empty person inside

MySelected has the same error.

You'll also have to fix some unclosed HTML tags. Additionally, I'd advice you to put your Save and Delete methods in MyViewModel rather than window.

Upvotes: 1

Related Questions