查看以下示例 HTML。它是一个简单的 KOforeach
绑定和一个用于将新项目添加到observableArray
. 添加工作正常,新项目出现。但是,该afterRender
方法永远不会被调用——不是在初始绑定之后,也不是在添加(和渲染)新项目之后。为什么?
小提琴:http: //jsfiddle.net/CQNm6
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>