【发布时间】:2015-09-24 15:32:15
【问题描述】:
这里有一些简单的代码来演示敲除模板的“后渲染”功能。当我点击按钮时,警告框会显示两次,而它应该只显示一次。
您可以在下面找到完整的代码。知道为什么警报框会出现两次吗?
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
</head>
<body>
<div data-bind="component: {name : 'foo-component', params: {onLoad: fooLoadedCallback}}"></div>
<!--foo-component params="onLoad: fooLoadedCallback"></foo-component-->
<script type="text/javascript">
ko.components.register('foo-component', {
//inner view model, only for this component in the template below.
viewModel: function(params) {
return {
status: ko.observable('Constructed'),
//this is called only after the template is rendered. This is called due to a statement in template.
componentLoaded: function () {
if (params.onLoad) {
params.onLoad(this);
}
$('button').click(function(){
alert("Rendered.");
});
}
};
},
template: '<h1>Hello</h1><br><button>Click me</button><br><span data-bind="text: status">Template</span>'
+'<span data-bind="template: { afterRender: componentLoaded() }"></span>',
});
//outer view model, for the div element.
var outerViewModel = {
fooLoadedCallback: function(viewModel) {
viewModel.status('Rendered!');
},
};
ko.applyBindings(outerViewModel);
</script>
</body>
</html>
【问题讨论】:
-
我想你的页面上有 2 个 foo-component,我认为你应该使用
-
第二个foo-component被注释掉了,我测试的时候还真把它删了。至于按钮,我知道那个语法;我的目标是测试后渲染器。请注意,我的问题不是关于如何使用按钮;这就是为什么警告框出现两次的原因。
-
对不起,我滚动得太快了,所以我没有看到 ko.components 上面的任何代码......无论如何,你能确认 componentLoaded 只被调用一次吗?
-
啊,当我加载页面时,componentLoaded 被调用了两次。为什么?我在 if(params) ... 正上方放置了一个警报,并且该警报显示了两次。
标签: javascript jquery knockout.js