如何在observableArray中生成对象列表

时间:2014-10-23 01:35:32

标签: knockout.js

我有这个json

"gm" : {
    "handlename1" : {
        "website" : "EOD",
        "mobile" : "1236",
        "prevwalk" : "mj,ann,",
        "createdat" : "datetimehere"
    },
    "handlename2" : {
        "website" : "PPO",
        "mobile" : "1236",
        "prevwalk" : "mj,ann,",
        "createdat" : "datetimehere"
    },
    "handlename3" : {
        "website" : "MTC",
        "mobile" : "1236",
        "prevwalk" : "mj,ann,",
        "createdat" : "datetimehere"
    }
}

并将其传递给observable数组,如果您在控制台日志中检查这是结果 enter image description here

如何将其放入表中并显示handlenames?

请停下来,谢谢

2 个答案:

答案 0 :(得分:1)

让思考变得更容易,只需将你的表头从每个json对象中放入(这就是我所做的)这不是不可能按照你的方式去做,只是痛苦的屁股

继承我的JS小提琴http://jsfiddle.net/sgg8uoy3/11/ 继承人HTML

<table style="width:100%">
  <tr data-bind="foreach: cols">
    <th data-bind="text: header"></th>
  </tr>
  <tr data-bind="foreach: cols">
    <td>
      <div data-bind="text: website"></div>
      <div data-bind="text: mobile"></div>
      <div data-bind="text: prevwalk"></div>
      <div data-bind="text: createdat"></div>
    </td>
  </tr>
</table>

JS:

var vm = (function(jsonData) {

var cols = ko.observableArray(jsonData.gm);
//$.each(jsonData.gm, function(i, item) {
//    cols.push(item);
//});
console.log(cols());

return {
    cols: cols   
} // the following just passes the json in kinda like a get request
})(JSON.parse('{"gm":[{"header":"handlename1","website":"EOD","mobile":"1236","prevwalk":"mj,ann,","createdat":"datetimehere"},{"header":"handlename2","website":"PPO","mobile":"1236","prevwalk":"mj,ann,","createdat":"datetimehere"},{"header":"handlename3","website":"MTC","mobile":"1236","prevwalk":"mj,ann,","createdat":"datetimehere"}]}'));
ko.applyBindings(vm);

哦,顺便说一句,我的json(将标题移动到每个gm对象中)是:

{
   "gm":[
      {
         "header":"handlename1",
         "website":"EOD",
         "mobile":"1236",
         "prevwalk":"mj,ann,",
         "createdat":"datetimehere"
      },
      {
         "header":"handlename2",
         "website":"PPO",
         "mobile":"1236",
         "prevwalk":"mj,ann,",
         "createdat":"datetimehere"
      },
      {
         "header":"handlename3",
         "website":"MTC",
         "mobile":"1236",
         "prevwalk":"mj,ann,",
         "createdat":"datetimehere"
      }
   ]
}

答案 1 :(得分:1)

我用JSFiddle做了一个有效的例子。我警告你:它不是非常优雅和简洁的代码,但是满足你的要求,这是我唯一能想到的。

说明:

foreach: handlenamesObs内,在每次迭代中,handlenamesObs数组中的一个对象绑定到$data变量。因此,在第一次迭代中,$data将是'handlename1',然后是'handlename2'等。这就是您要显示handlenames的部分。

然后,当我使用with: $root.gm[$data]时,我说“好吧,在当前元素中的任何元素中,我的$data对象不是'handlename1'字符串,而是我的对象是gm['handlename1'],在<span>内,我想显示此website对象的gm['handlename1']属性。

使用$root是因为,如果不使用它,knockoutjs会在gm[$data]内部寻找$data属性。由于$data只是字符串'handlename1',因此调用'handlename1'.gm[$data]没有任何意义。因此,我们不想从隐式gm[$data]对象调用$data,而是在根范围内调用它,即ViewModel实例本身。