5
看看下面的示例HTML。這是一個簡單的KO foreach
裝訂和一個按鈕來添加一個新項目到observableArray
。加法工作正常,新項目顯示。但是,從不調用afterRender
方法 - 不是在初始綁定之後,而是在添加(和呈現)新項目之後。爲什麼?爲什麼afterRender從來沒有打過電話?
HTML
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
</head>
<body>
<div data-bind="foreach: data.things, afterRender: afterRenderTest">
<h1 data-bind="text: name"></h1>
</div>
<a href="JavaScript:void(0);" onclick="data.things.push({ name: ko.observable('New Thing') });">Add New Thing</a>
<script type="text/javascript">
var Thing = (function()
{
function Thing(p_name)
{
this.name = ko.observable(p_name);
}
return Thing;
})();
var data =
{
things: ko.observableArray(
[
new Thing("Thing One"),
new Thing("Thing Two"),
new Thing("Thing Three")
])
};
function afterRenderTest(elements)
{
alert("Rendered " + elements.length + " elements.");
}
ko.applyBindings();
</script>
</body>
</html>
傻我,謝謝! –