googleuser googleuser - 1 month ago 7
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();

viewmodel.person.push(x);


Finally binded the elements

ko.applyBindings(viewmodel);


Here is the JSFIDDLE I trying to achieve

http://jsfiddle.net/GSvnh/5592/

I want the following output

firstname lastname
bob marley
tom brady
George clooney

Answer

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: http://jsfiddle.net/GSvnh/5593/

Also the SO Docs page has a working foreach example

Comments