gpt4 book ai didi

data-binding - 为什么从不调用 afterRender?

转载 作者:行者123 更新时间:2023-12-04 17:01:41 24 4
gpt4 key购买 nike

查看以下示例 HTML。这是一个简单的 KO foreach绑定(bind)和一个按钮以将新项目添加到 observableArray .添加工作正常,新项目出现。但是,afterRender方法永远不会被调用 - 不是在初始绑定(bind)之后,也不是在添加(和渲染)新项目之后。为什么?

fiddle : 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>

最佳答案

你的语法是错误的,因为 foreach绑定(bind)采用数组或对象,您可以在其中指定其他事件、参数。

来自 documentaiton:

Pass the array that you wish to iterate over. The binding will output a section of markup for each entry.

Alternatively, pass a JavaScript object literal with a property called data which is the array you wish to iterate over. The object literal may also have other properties, such as afterAdd or includeDestroyed...



所以你需要写:
<div data-bind="foreach: { data: data.things, afterRender: afterRenderTest }">
<h1 data-bind="text: name"></h1>
</div>

演示 JSFiddle.

关于data-binding - 为什么从不调用 afterRender?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com