googleuser googleuser - 10 months ago 41
Javascript Question

How do i push elements to javascript object in knockout

I am trying to learn knockout.I am trying to learn foreach binding in knockout .

First I declared a javascript object

var people = function()
var self = this;
this.firstname = ko.observable("")
this.lastname = ko.observable("")

I tried to push elements into the javacript object

var x = new people();

x.push({firstName: "bob" ,lastName:'gill'});

I added viewmodel

function TestViewModel()
var self = this;
this.person = ko.observableArray({people});


created an instance of viewmodel and pushed the elements

var viewmodel = new TestViewModel();


Finally binded the elements


Here is the JSFIDDLE I trying to achieve

I want the following output

firstname lastname
bob marley
tom brady
George clooney

Answer Source

You have a couple issues to address in your JSFiddle:

  1. Your thead HTML is missing a closing >
  2. As user nnnnnn mentioned, you are trying to push to an instance of People, not the array that is bound to your foreach
  3. Your value bindings do not match your people property names (firstname vs firstName)

Here's an updated JSFiddle that implements a basic foreach example:

Also the SO Docs page has a working foreach example