How to pass a reference to aframe component?

强颜欢笑 提交于 2019-12-12 10:05:23

问题


I'm writing a custom aframe component to render a mesh based on a very long array of objects.

Aframe documentation only lists array as an input type where you can pass an attribute and it will be parsed into an array attributename="1 2 3"

I would like to pass a javascript reference into the component from the outside with something like this:

const hugeArray = [{somejson}, ...]
const element = document.createElement('my-component');
element.<something happens here>

or create a component outside of DOM API and pass arguments to component's init method.


回答1:


Use setAttribute, which can take objects and arrays as well. Go through the schema rather than calling a method since the init handler will automatically get called for you at the right time.

https://aframe.io/docs/0.5.0/core/entity.html#setattribute-attr-value-componentattrvalue

AFRAME.registerComponent('mycomponent', {
  schema: { 
    yourData: {type: 'array'}
  },

  init: function () {
    console.log(this.data.yourData);
  }
});

const hugeArray = [{somejson}, ...]
const element = document.createElement('a-entity');
element.setAttribute('mycomponent', {yourData: hugeArray});
scene.appendChild(element);



回答2:


Found one way to do it.

const hugeArray = [{somejson}, ...]
const element = document.createElement('a-entity');
element.setAttribute('mycomponent', '');
//... add component to DOM and let it initialize
element.components.mycomponent.customMethod(hugeArray);

All that is assuming component is registered under a name "mycomponent" and has a method customMethod alongside init etc.



来源:https://stackoverflow.com/questions/42854921/how-to-pass-a-reference-to-aframe-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!