2014-10-10 63 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