问题描述
我有一个使用3.2.0的嵌套KnockoutJS组件的层次结构。它工作得很好但是我希望在加载和渲染整个组件层次结构后执行一些代码。它与afterRender()完全相同,与afterRender相同的常见用例需要。
I have a hierarchy of nested KnockoutJS Components using 3.2.0. It's working very well but I'm looking to execute some code once my entire hierarchy of components has been loaded and rendered. It's a rough equivalent of afterRender(), needed for the same common uses cases as afterRender.
我尝试了几种方法但到目前为止没有运气:
I've tried a few approaches but no luck so far:
- 在根模板中添加了以下内容,但在嵌套组件加载之前调用它,所以太早了。
<! - ko模板:{afterRender:onLoad.bind($ data)} - >
- 使用最新的3.3.0-alpha并在所有组件上指定synchronous:true。但我相信,因为我使用AMD,组件仍然是异步加载,这意味着只是因为我的root applyBindings()返回,并不意味着所有组件都已加载和呈现。
- 甚至尝试构建一个只在加载相应组件时才能解析的延迟对象集合。这变得过于复杂,但由于我不愿意这样做仍然无法工作。
有没有办法获得回电一旦敲除了knockoutjs组件的完整层次结构并被渲染了吗?谢谢!
Is there a way to get a callback called once a complete hierarchy of knockoutjs components have been loaded and rendered? Thanks!
我刚刚遇到这两个线程,所以似乎其他人也在寻找这个。与现有解决方法的关键区别在于它们不适用于嵌套组件。
I just came across these two threads so it seems others are looking for this as well. The key differentiator from the existing workarounds are they don't work with nested components.
- https://github.com/knockout/knockout/issues/1533
- https://github.com/knockout/knockout/issues/1475
推荐答案
我编写了一个淘汰库,在所有组件都已加载和绑定时触发事件。它使用引用计数,类似于用于垃圾收集的引用计数。我在我的项目中广泛使用组件,包括嵌套很多层次,我不能不知道什么时候准备就绪。我没有花太多时间在使用文档上,但基础知识就在那里。
I've written a knockout library that triggers an event when all components have been loaded and bound. It uses reference counting, similar to referencing counting used for garbage collection. I extensively use components in my project(s), including nesting many levels deep, and I can't live without knowing when everything is "ready to go". I haven't spend much time on documentation of usage, but the basics are there.
Git Hub wiki:
Git Hub wiki:https://github.com/ericraider33/ko.component.loader/wiki
小提琴:
使用HTML:
<div id="ko-div">
Status: <span data-bind="text: loading() ? 'Loading' : 'Done'"></span>
<br><br>
<test-panel></test-panel>
</div>
用法JS:
var pageModel = {
loading: ko.observable(true),
completedCallback: function (childRef) {
pageModel.loading(false);
childRef.testValue(childRef.testValue()+1);
}
};
var tpRef = ko.componentLoader.ref.child({ completedCallback: pageModel.completedCallback});
var tpModel = {
attached: function(element) { return tpRef; },
testValue: ko.observable(5)
};
ko.components.register('test-panel', {
viewModel: function() { return tpModel; },
template: '<div data-bind="attached: true">Test Panel<br>From Code <span data-bind="text: testValue"></span></div>'
});
ko.componentLoader.setOptions({ verbose: true });
ko.applyBindings(pageModel, $('#ko-div')[0]);
这篇关于当所有嵌套组件都被渲染时,KnockoutJS afterRender回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!