Reputation: 13
I want to call some function (foo) from another javascript file (a.js) when inside my AFRAME component's init function.
in my index.html something like this:
<script type="module">
import {foo} from "a.js";
AFRAME.registerComponent('registerevents', {
init: function () {
foo();
}
}
}
when I did this, the init function doesn't even get called.
Then I tried something like this:
<script type="module" src="a.js"></script>
<script>
AFRAME.registerComponent('registerevents', {
init: function () {
foo();
}
}
}
I got a function not defined in this case.
Then I tried in a.js
window.foo = foo;
in my index.html:
<script type="module" src="a.js"></script>
<script>
AFRAME.registerComponent('registerevents', {
init: function () {
window.foo();
}
}
}
Then I got a window.foo is not a function error. What should be the correct way to call a function in the init function? Thanks !
Upvotes: 1
Views: 1553
Reputation: 51
You can do something like this:
const AFRAME = window.AFRAME;
const Initialize = () => {
AFRAME.registerComponent("a-scene", {
schema: {
background: { type: "color", default: "#000" },
},
});
};
and then useEffect:
useEffect(()=>{
Initialize()
})
Upvotes: 0
Reputation: 46
Modules and A-Frame work fine. The problem is that the init method is not called until a component is set on an entity. For instance, you can set it on a-scene
as follows:
<script type="module">
import {foo} from './a.mjs';
AFRAME.registerComponent('registerevents', {
init: function () {
foo();
}
});
AFRAME.scenes[0].setAttribute('registerevents','');
</script>
Where a.mjs is:
export function foo(){ console.log('Fooing is believing!')}
Working example: https://glitch.com/edit/#!/little-coral
Upvotes: 2