How to pass a reference to aframe component?

2019-08-01 02:40发布

问题:

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.