knockoutjs中的动态表

时间:2012-12-20 10:52:16

标签: html knockout.js

我正在使用ajax调用来获取数据,以json格式返回数据,如下所示:

{ "d" : [ 
  { "Goal" : "Some one client",
    "GoalID" : 1,
    "IsPublic" : true,
    "MemberName" : "user1"
  },                                         
  { "Goal" : " this is goal",
    "GoalID" : 1,
    "IsPublic" : false,
    "MemberName" : "user2"
  },           
  { "Goal" : "Get call",
    "GoalID" : 4,
    "IsPublic" : true,
    "MemberName" : "user2"
  }
] }

现在在我的html页面中,我想为每个用户创建单独的表。这是我的表

//want username here then table for goal of that user 
<table>
  <thead>
     <tr class="headerRow">
      <th>member</th>
      <th>
         Goals
       </th>
        </tr>
        </thead>
      <tbody data-bind="foreach: tasks">
      <tr">
       <td>
          <span data-bind="text: members" />
        </td>
        <td>
           <span data-bind="text: goal" />
         </td>
       </tr>
      </tbody>
</table>

“task”是包含所有目标细节的可观察数组。

这是我在javascript中的目标构造器

 function Goal(data) {
    var self = this;
    self.goalID = data.GoalID;
    self.goal = data.Goal;
    self.isPublic = ko.observable(data.IsPublic);
    self.members = ko.observable(data.MemberName);
}

1 个答案:

答案 0 :(得分:0)

也许它不是最好的解决方案,但它会起作用。添加计算,返回所有用户:

self.users = ko.computed(function(){
    var list = ko.utils.arrayMap(self.tasks(), function(item){
        return item.members
    });
    return ko.utils.arrayGetDistinctValues(list);
});

使用foreach绑定为每个用户创建一个表:

<div data-bind="foreach: users">
    <table>
      <thead>
         <tr>
          <th>membername</th>
          <th>
             Goals
           </th>
            </tr>
            </thead>
          <tbody data-bind="foreach: $parent.tasks">
          <tr data-bind="if: members == $parent">
           <td>
              <span data-bind="text: members" />
            </td>
            <td>
               <span data-bind="text: goals" />
             </td>
           </tr>
          </tbody>
    </table>
</div>

这是工作小提琴:http://jsfiddle.net/TQXja/4/