2014-10-10 61 views
0

我想用knockout.js渲染一个依赖列表,但是我的问题是我不知道在对象之前有多少个子对象。它可能不是一,三百级的孙子。当深度未知时,挖掘渲染依赖列表

这是我从列表中只有一个级别读取数据时的例子:

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title></title> 
     <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script> 
     <link rel="stylesheet" href="style.css"> 
    </head> 
    <body> 

     <ul data-bind="template: { name: 'friendTemplate', foreach: friends, as: 'friend' }"></ul> 

     <!-- Template --> 
     <script type="text/html" id="friendTemplate"> 
      <li> 
       <strong data-bind="text: fullName"></strong> 
       id: <span data-bind="text: id"></span>, 
       parentId: <span data-bind="text: parentId"></span> 
      </li> 
     </script> 

     <script type="application/javascript"> 
      function friend(id, parentId, firstName, lastName) { 
       this.id = id; 
       this.parentId = parentId; 
       this.profilePicture = ""; 
       this.firstName = firstName; 
       this.lastName = lastName; 
       this.friends = ko.observableArray(); 

       this.fullName = ko.computed(function() { 
        return firstName + " " + lastName; 
       }); 
      } 

      function userViewModel(id) { 
       this.id = id; 
       this.profilePicture = ""; 
       this.firstName = ko.observable("Bert"); 
       this.lastName = ko.observable("Bertington"); 
       this.friends = ko.observableArray(); 

       this.fullName = ko.computed(function() { 
        return this.firstName + " " + this.lastName; 
       }); 
       this.addFriend = function() { 
        this.friends.push(new friend(-1, this.id, 'John', 'Doe')); 
       }.bind(this); 
      } 
      var user = new userViewModel(1); 
      ko.applyBindings(user); 

      var friend1 = new friend(0, user.id, 'Patty', 'Smith'); 
      friend1.friends.push(new friend(0, user.id, 'Henry', 'Bellard')); 

      user.friends.push(friend1); 
      user.friends.push(new friend(1, user.id, 'George', 'Maddison')); 
      user.friends.push(new friend(2, user.id, 'Takashi', 'Hendrixsson')); 
      user.friends.push(new friend(3, user.id, 'Bella', 'Suffeur')); 
     </script> 
    </body> 
</html> 

正如你可以看到在列表中的第一个朋友也有一个朋友,在理论上这个朋友也可以有一个朋友。

那么,如果我不知道雏鸟的级别,我该如何渲染这些朋友呢?我是否必须通过JQuery或其他方式动态添加这些元素?

+0

所以那里有大约unobstrousive淘汰赛http://knockoutjs.com/documentation/unobtrusive-event-handling一个很好的例子.html – 2014-10-10 15:11:05

回答

1

你会使用递归来解决这个问题。您需要添加使用相同的模板里内的另一个UL:

<!-- Template --> 
<script type="text/html" id="friendTemplate"> 
    <li> 
     <strong data-bind="text: fullName"></strong> 
     id: <span data-bind="text: id"></span>, 
     parentId: <span data-bind="text: parentId"></span> 
     <ul data-bind="template: { name: 'friendTemplate', foreach: friends, as: 'friend' }">  
     </ul> 
    </li> 
</script> 

http://jsfiddle.net/Wk7dr/11/

+0

虽然此链接可能回答此问题,但最好在此处包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 – 2014-10-10 15:45:59

+0

@DavidCrowell好的。我会更新答案 – 2014-10-10 15:46:38