具有Observable属性的Knockout Observable数组的JSON对象数组

时间:2015-10-22 11:06:56

标签: javascript jquery json knockout.js observable

我的应用程序有一个ajax调用,它将返回一组JSON对象。

String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");

然后我需要将它们分配给一个可以观察到对象属性的knockout observable数组。

我可以毫无问题地创建可观察数组。

[
{"ID":2,"Name":"Name 1","CreatedOn":"/Date(1432892160000)/"},
{"ID":7,"Name":"Name 2","CreatedOn":"/Date(1432892160000)/"},
{"ID":8,"Name":"Name 3","CreatedOn":"/Date(1432892160000)/"},
{"ID":9,"Name":"Name 4","CreatedOn":"/Date(1432892160000)/"},
{"ID":10,"Name":"Name 5","CreatedOn":"/Date(1432854000000)/"}
]

但是,我无法推断如何推送到可观察数组并使每个对象的属性可观察。

1 个答案:

答案 0 :(得分:4)

使用Knockout Mapping Plugin。这样的事情应该有效

function vm(result){
  var self = this;
  self.items = ko.observableArray();
  ko.mapping.fromJS(result.ReturnedObjects,{},self.items)
  console.log(self.items()); //array with each object props as observables
}