简体   繁体   中英

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

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/

To answer it, follow an example, which I have an amount of information into a base of data and I will push it into a data table in my front-end.

function tableData(){
 <cfoutput>
    var newDados = #serializeJSON(mySQLData)#;
    var dataABC = newDados.ABC;
    var dataXYZ = newDados.XYZ;
  </cfoutput>
  //cfoutput is a Cold Fusion parameter to receive data from SQL.

In this case I serialize newDados to an object. ABC and XYZ are objects sons of newDados.

In this case, I want to mix and push both objects child in a single object to work these parameters together. So I use a forEach function:

  allData = new Array();

  dadosABC.forEach(function(obj){
    allData.push(obj);
  });
  XYZ.forEach(function(obj){
    allData.push(obj);
  });
  //Here allData have already receiving data of both newDados object child

  allDataSize = allData.length;
  for (var i = 0; i < sizePreenc; i++) {
    allData[i] = new Array();
    tableData[i].push(allData[i]);
    tableData[i].push(allData[i].firstName);
    tableData[i].push(allData[i].lastName);
    tableData[i].push(allData[i].age);
    tableData[i].push(allData[i].gender);
  };
  drawGrid('');
 }; 

This way, I push my datas to table, or whatever I want to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM