naugtur
naugtur

Reputation: 16915

How to pass a reference to aframe component?

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.

Upvotes: 2

Views: 2322

Answers (2)

ngokevin
ngokevin

Reputation: 13233

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);

Upvotes: 3

naugtur
naugtur

Reputation: 16915

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.

Upvotes: 2

Related Questions