在 A-Frame 组件上,如何在函数之间共享数据?
On an A-Frame component, how do you share data between functions?
我正在制作一个 A-Frame 组件,我想在 init
等函数和其他自定义组件处理程序之间共享数据。
我想出了如何添加到组件架构以允许来自 DOM 的输入,以便使用 this.data
遵循此文档来设置变量:
https://aframe.io/docs/0.4.0/core/component.html#component-prototype-properties
但是我遇到了麻烦,有时 this.data
的值会从 DOM 恢复到初始状态,而不反映运行时修改。有没有更好的方法来跨组件共享数据?
在A-Frame组件中有两种推荐的数据存储方式,类似于public和私有属性。
架构 (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
}
});
属性(私有)
对于要在组件中使用的数据,您也可以将它们直接分配给 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
}
});
我正在制作一个 A-Frame 组件,我想在 init
等函数和其他自定义组件处理程序之间共享数据。
我想出了如何添加到组件架构以允许来自 DOM 的输入,以便使用 this.data
遵循此文档来设置变量:
https://aframe.io/docs/0.4.0/core/component.html#component-prototype-properties
但是我遇到了麻烦,有时 this.data
的值会从 DOM 恢复到初始状态,而不反映运行时修改。有没有更好的方法来跨组件共享数据?
在A-Frame组件中有两种推荐的数据存储方式,类似于public和私有属性。
架构 (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
}
});
属性(私有)
对于要在组件中使用的数据,您也可以将它们直接分配给 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
}
});