我'm using Aurelia' s EventAggregator
在我的应用中发布和订阅活动 . 我的一些自定义元素需要一段时间来加载,所以我使用 loading
事件告诉我的主 app.js
在加载期间向页面添加微调器 .
一旦应用程序加载并且我开始在路由之间切换,这可以正常工作,但是,在第一页加载时 subscribe
方法拾取事件 .
这基本上是我的 app.js
所做的:
attached () {
this.mainLoadingSubscription = this.eventAggregator.subscribe('main:loading', isLoading => {
// If main is loading
if (isLoading) {
document.documentElement.classList.add('main-loading');
}
// Stopped loading
else {
document.documentElement.classList.remove('main-loading');
}
});
}
这是我的自定义元素的作用:
constructor () {
this.eventAggregator.publish('main:loading', true);
}
attached () {
this.doSomeAsyncAction.then(() => {
this.eventAggregator.publish('main:loading', false);
});
}
这会导致第一页加载不显示微调器,而页面看起来有点破碎 .
顺便说一句,我知道你可以从元素的 attached
方法返回一个 Promise
,但由于this other problem我不能这样做
1 回答
在viewModel的构造函数中设置订阅或激活回调
在上面的示例中,您在viewModel的
attached()
回调中设置了订阅 . 不幸的是,在调用所有子自定义元素的attached()
回调之前不会调用它,这在调用任何一个自定义元素的constructor()
函数之后很久 .试试这个:
app.js
如果viewModel是可以导航到的路由,则在
activate()
回调中处理此问题,并在deactivate()
回调中进行适当的拆卸 .