aframe - 组件依赖关系如何在 A-frame 中工作?
问题描述
我试图了解依赖项在 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>
这是这个例子的一个小提琴,它显示了它是如何不工作的,值为testString
is 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。这是一个按我预期工作的小提琴。
那么并不dependencies
意味着等待指定的组件被加载/初始化?还是我做错了什么?如有必要,我可以使用 eventListener 解决这个问题,但我想更好地理解这一点,以及是否有更好的方法来实现这一点。
任何建议一如既往地受到赞赏,如果您需要更多信息来理解问题,请告诉我。
解决方案
组件依赖关系适用于同一实体上的组件,而不是跨实体(如卫星/母舰组件示例)。像你一样使用加载的事件是要走的路。
推荐阅读
- reactjs - 为什么反应排序相反?
- python - 如何在 URL Flask 中显示当前用户的用户名
- flutter - 错误:找不到类型“鼠标光标”。(fl_chart)
- reactjs - 未找到模块:无法解析 'swiper/css
- git - 无法使用个人访问令牌访问私有 Git 存储库
- javascript - 如何在 Shinyalert 中使用 HTML 和 JavaScript?
- php - 从特定值 php 数组计算
- django - 在 POST ajax 上获取空字典
- javascript - React Native Navigation 返回另一个导航器中的两个屏幕
- spring-cloud-netflix - 添加 feign-client 依赖会导致错误!我无法启动应用程序