[英]On an A-Frame component, how do you share data between functions?
I'm making an A-Frame component and I want to share data between functions like init
and other custom component handlers. 我正在制作一个A-Frame组件,我想在init
和其他自定义组件处理程序之类的函数之间共享数据。
I figured out how to add to the component schema to allow for input from the DOM to set a variable using this.data
following this doc: https://aframe.io/docs/0.4.0/core/component.html#component-prototype-properties 我想出了如何添加到组件架构中以允许来自DOM的输入,以使用遵循此文档的this.data
设置变量: https : //aframe.io/docs/0.4.0/core/component.html#component -prototype的属性
However I am having trouble, sometimes the value of this.data
reverts back to the initial state from the DOM, not reflecting runtime modifications. 但是我遇到了麻烦,有时this.data
的值会从DOM恢复为初始状态,而不反映运行时的修改。 Is there a better way to share data across a component? 是否有更好的方式在组件之间共享数据?
There are two recommended ways of storing data in an A-Frame component, similar to public and private properties. 有两种建议的将数据存储在A-Frame组件中的方式,类似于公共属性和私有属性。
Schema (public) 模式(公共)
Properties declared in the component's schema are public, and can be set with setAttribute
and accessed with both getAttribute
and this.data.____
. 组件模式中声明的属性是公共的,可以使用setAttribute
进行设置,并可以使用getAttribute
和this.data.____
访问。 NOTE: It is not safe to modify this.data
directly, because A-Frame will overwrite the data when receiving updates from the DOM. 注:这是不是安全的修改this.data
直接,因为从DOM接收更新时,A型架将覆盖数据。
HTML: HTML:
<a-entity foo="bar: 10"></a-entity>
JS: 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
}
});
Properties (private) 属性(私有)
For data meant to be used within a component, you can also assign them directly to this
. 对于要在组件内使用的数据,您还可以将它们直接分配给this
。 This is the best option when data will only be used within the component, and doesn't need to be declared in the HTML. 当数据仅在组件内使用并且不需要在HTML中声明时,这是最佳选择。
JS: 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
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.