问题
I am trying to extend the a-animation component but override some functionality.
I want to add a state attribute to the parent "el", and only if the parent has that state will a mouseenter event actually trigger the animation.
I am hoping I don't need to re-write or require a Pull request to facilitate this additional functionality as that will slow down testing and usability for me, but I would like to be able to use the main code and only "add or override" functionality.
回答1:
I came here looking for the same answer, "How to extend a component". I wanted to write some custom logic for the look-controls component, so I'll share what I learned about extending components.
First of all, I would recommend doing a copy on the component to avoid doing any damage to the original component (just in case you are using it elsewhere). I am using Angular, so I have a nice utility for a deep copy, but you can use whatever you like. (It looks like A-Frame has some utilities that might do this, but there are no docs as to how to use them: AFRAME.utils.extend, AFRAME.utils.extendDeep). Copying is up to you.
Anyways, here is how you can extend an existing component:
// Get a copy of the original component.
var customLookControls = angular.copy(AFRAME.components['look-controls']),
customLookControlsComponent = customLookControls.Component;
// Add your custom logic to component.
customLookControlsComponent.prototype.myNewMethod = function() { // Something awesome. };
Here is how you would register it:
AFRAME.registerComponent('custom-look-controls', customLookControls);
And finally, here is how you would use it:
<a-entity custom-look-controls></a-entity>
UPDATE
Locally I found that creating a new component based off of an existing one, was not working the way I had expected it to. So, in a much simpler way, I found it is pretty easy to extend an existing component:
// Get a reference to the component we want to extend.
var lookControls = AFRAME.components['look-controls'],
lookControlsComponent = lookControls.Component;
/**
* Overrides the Touch event handler...
* @param {!Event} e The touch event object.
*/
lookControlsComponent.prototype.onTouchMove = function(e) {
// Replace the TouchMove event handler...
};
/**
* New/custom method...
*/
lookControlsComponent.prototype.somethingNew = function() {
// My awesome logic here.
};
回答2:
You can use JavaScript to trigger the animation whenever you want.
<a-entity id="foo">
<a-animation begin="bar"></a-animation>
</a-entity>
if (whateverCondition) {
document.querySelector('#foo').emit('bar');
}
Or using the animation component (https://github.com/ngokevin/kframe/tree/master/components/animation):
<a-entity id="foo" animation="startEvents: bar"></a-entity>
if (whateverCondition) {
document.querySelector('#foo').emit('bar');
}
来源:https://stackoverflow.com/questions/41478249/aframe-extend-component-and-override