我想用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或其他方式動態添加這些元素?
所以那裏有大約unobstrousive淘汰賽http://knockoutjs.com/documentation/unobtrusive-event-handling一個很好的例子.html – 2014-10-10 15:11:05