在el加载之前但在加载事件发出之前的自定义组件运行功能

时间:2019-01-03 13:13:16

标签: aframe

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

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

有没有办法解决这个问题,并且有一个自定义事件,例如'components-loaded'

我试图避免加载事件,因为它会干扰其他需要此事件的逻辑,同时仍在监视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()
      }
    });
  }  
});

1 个答案:

答案 0 :(得分:0)

您可以使用事件代替计时器-在完成预加载的内容后发出事件:

 _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])
   }
}

在我的fiddle中进行检查。