组件依赖如何在A帧中起作用?

问题描述 投票:0回答:1

我试图理解依赖关系如何在A帧组件中工作,因为它似乎不像我想象的那样工作。

场景,我正在尝试创建一种“母舰”组件来存储全局信息,可以在体验的不同阶段从不同的组件访问。为此,我将一个组件附加到a-scene,然后我将“卫星”组件附加到该场景的子实体。

问题是,在加载时,母舰组件似乎没有及时初始化以便访问其属性。我想如果我将母舰组件添加为卫星组件的dependency,它会等待它初始化,但它似乎不起作用。

见下面的组件;

//the mothership component
 AFRAME.registerComponent('mothership', {  
        schema: {
          testString: {type: 'string', default: 'Working'},
        },
        init: function(){
        },
 }),

//the satellite component
  AFRAME.registerComponent('satellite', {     

        dependencies: ['mothership'],

        init: function(){

          var mother = this.el.sceneEl
          var self = this.el

          var message = mother.getAttribute('mothership').testString
          //to demonstrate problem
          self.setAttribute('value', message)
          console.log(message)
          //-> undefined

        },
 })

和HTML

 <a-scene mothership>
      <a-text 
        satellite
        position="0 1.6 -3"
        color="black"
        align="center"
        value="">
      </a-text>
 </a-scene>

这个例子的Here is a fiddle显示它是如何工作的,testString的值是undefined

我已经设法通过在等待母舰的eventListener事件的卫星组件中添加loaded来使这两个组件之间的连接起作用。见下面的例子和小提琴。

      //the mothership component
      AFRAME.registerComponent('mothership', {  
        schema: {
          testString: {type: 'string', default: 'Working'},
        },
        init: function(){
        },
      }),

      //the satellite component
      AFRAME.registerComponent('satellite', {     

        dependencies: ['mothership'],

        init: function(){

          var mother = this.el.sceneEl
          var self = this.el

          //wait for mothership to be loaded
          mother.addEventListener('loaded', function(){
            var message = mother.getAttribute('mothership').testString
            //to demonstrate problem
            self.setAttribute('value', message)
            console.log(message)
          })

        },
      })

使用与原始示例相同的HTML。那个按照我的预期工作的Here is a fiddle

那么dependencies是不是意味着等待加载/初始化指定的组件?或者我做错了什么?如果有必要,我可以使用eventListener解决这个问题,但我想更好地理解这一点,如果有更好的方法来实现这一点。

任何建议都一如既往地受到重视,如果您需要更多信息来了解问题,请告诉我。

aframe
1个回答
1
投票

组件依赖性适用于同一实体上的组件,而不是像您的卫星/母舰组件示例那样的实体。像你一样使用加载的事件是要走的路。

© www.soinside.com 2019 - 2024. All rights reserved.