aframe-event-decorators
Decorate component functions to have them automatically subscribe/unsubscribe to events.
For A-Frame.
API
Decorate your functions in your Component definitions to make them bind and unbind from events automatically. With this package there is no need to call addEventListener/removeEventListener, just create normal functions in your components augmented with a decorator functor.
Decorate your functions before calling AFRAME.registerComponent. Here is the simplest example:
const bindEvent = bindEvent; AFRAME
By default the function will be bound to events corresponding to its property name, in this case: 'componentchanged'. It will listen for events on its parent element, and will begin listening or end listening when init or remove is called. However this can also be configured by passing a configuration object:
AFRAME
There is also the bindEventPlayPause convenience decorator which will always bind/unbind in play and pause respectively.
Functions will only be bound to events when a new component is created. Decorating a function with bindEvent() in a components init, or tick functions for example will have no effect. Don't bind to arrow functions because they don't have their own this attribute.
Installation
npm
Install via npm:
npm install aframe-event-decorators
Then require and use.
;;
Create your own decorators
This next bit may or may not be useful to anyone. You dont need to know any of what follows to use the event decorators.
I've also exposed an abstract component decorator system so you can create your own decorators. These decorators are special because they are only executed when a component is instantiated, with their this attribute set to the new instance. The event binding decorators are built on top of this. Here's an example:
const decorate = decorate; // It's useful to wrap the Functor object to create a closure with any data, such as this 'message' parameter. { // This function will be executed when the component which has a decorated function is instanciated. 'this' will be set // to the instance and 'funcPropertyName' is the property name which maps to the decorated function. The functor should // return a function. { const func = thisfuncPropertyName; // 'this' is assigned to the component instance. // Functor should return a function return { console; return func; } } return } // Now our new decorator 'sayHello' is ready to be used in a Component definition.AFRAME // Whenever the 'foo' component is added to an Entity its play function is augmented with a message that has details// about the component instance!