我正在制作一个 A-Frame 组件,我想在 init
等函数和其他自定义组件处理程序之间共享数据。
我想出了如何添加到组件模式以允许来自 DOM 的输入,以使用此文档后的 this.data
设置变量:
https://aframe.io/docs/0.4.0/core/component.html#component-prototype-properties
但是我遇到了麻烦,有时 this.data
的值会从 DOM 恢复到初始状态,而不是反射(reflect)运行时修改。有没有更好的方法来跨组件共享数据?
最佳答案
在 A-Frame 组件中有两种推荐的数据存储方式,类似于公共(public)属性和私有(private)属性。
架构(公共(public))
在组件架构中声明的属性是公共(public)的,可以使用 setAttribute
设置并使用 getAttribute
和 this.data.____
访问. 注意:直接修改 this.data
是不安全的,因为 A-Frame 在从 DOM 接收更新时会覆盖数据。
HTML:
<a-entity foo="bar: 10"></a-entity>
JS:
AFRAME.registerComponent('foo', {
schema: {
bar: {default: 25}
},
init: function () {
console.log(this.data.bar); // 10
this.data.bar = 5; // THIS CHANGE MAY BE LOST.
},
doStuff: function () {
console.log(this.data.bar); // 10
this.el.setAttribute('bar', 'foo', 15);
console.log(this.data.bar); // 15
}
});
属性(私有(private))
对于要在组件中使用的数据,您也可以将它们直接分配给 this
。当数据仅在组件内使用且不需要在 HTML 中声明时,这是最佳选择。
JS:
AFRAME.registerComponent('foo', {
init: function () {
this.baz = 'hello';
console.log(this.baz); // hello
},
doStuff: function () {
console.log(this.baz); // hello
this.baz = 'bonjour';
console.log(this.baz); // bonjour
}
});
关于javascript - 在 A-Frame 组件上,如何在函数之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42244750/