自定义组件在加载el之前运行函数,但在发出已加载事件之前运行



我正在编写一个自定义函数,它要求初始化所有组件(包括它自己)。

一旦初始化了所有组件,但在发出加载的事件之前,我想在el上运行一些自定义逻辑,然后释放加载的事件。

有没有办法处理这个问题,有没有像"组件加载"这样的自定义事件

我试图避免加载的事件,因为它会干扰其他需要此事件的逻辑,同时仍在监视dom。

AFRAME.registerComponent('cool-component', {
init: function() {
this.preloadBound = this._preload.bind(this);
this.el.addEventListener('components-loaded', this.preloadBound, {once: true});
this.el.addEventListener('componentinitialized', this.preloadBound, {once: true});
this.el.addEventListener('componentchanged', this.preloadBound, {once: true});
this.el.addEventListener('componentremoved', this.preloadBound, {once: true});
this.el.addEventListener('child-attached', this.preloadBound, {once: true});
this.el.addEventListener('child-detached', this.preloadBound, {once: true});
this.preloaded = false; <-- CREATED BOOL FLAG
},
_preload: function() {
//do some work here
this.preloaded = true;
}
exposed:function(){ <-- UPDATED THIS FUNCTION
return new Promise((resolve,reject)=>{
if(!this.preloaded){
setTimeout(() => {
this.exposed().then(resolve);
}, 200);
}
else{
//do some work based on the work done in the preload
resolve()
}
});
}  
});

您可以使用事件而不是计时器-在预加载的东西完成时发出事件:

_preload: function() {
//do some work here
emit('preloaded_done')
this.preloaded = true;
},
exposed:function(){ 
if (!this.preloaded) {
this.el.addEventListener('preloaded_done', this.exposed)
return;
}
// all things that are needed to be done after the preload
}

通过这种方式,在预加载的东西完成后,将执行公开的函数。


或者您可以将事件存储在阵列中

init: function() {
// ... binds and stuff
this.cachedEvents = []
this.el.addEventListener('loaded', this.cacheEvents)
stuffBeforeEmittingEvents()
},
cacheEvents: function(e) {
this.cachedEvents.push(e)
this.el.removeEventListener(e.type, this.cacheEvents)
e.stopPropagation()
}

一旦你做了你的事情,只需循环并发射

for(i = 0; i < this.cachedEvents.length;  i++) {
this.el.emit(this.cachedEvents[i].type, this.cachedEvents[i])
}


类似的东西:

init: function() {
this.events = []
this.stuff = this.stuff.bind(this);
this.cacheEvents = this.cacheEvents.bind(this);
this.emitCachedEvents = this.emitCachedEvents.bind(this);
this.el.addEventListener('loaded', this.cacheEvents)
this.stuff()
},
stuff: function() {
// whatever you need to do
this.emitCachedEvents()
},
cacheEvents(e) {
this.events.push(e)
// prevent bubbling + catching the same event
this.el.removeEventListener(e.type, this.cacheEvents)
e.stopPropagation()
},
emitCachedEvents() {
for (let i = 0; i < this.events.length; i++) {
// primitive, may require polyfill - emit(name, data)
emit(this.events[i].type, this.events[i])
}
}

看看我的小提琴。

最新更新