1

While switching from Mootools to EcmaScript Classes I need to add some pre-built functionalities to classes. Like events...

Mootools uses an Implements parameter in Class for this.

var Widget = new Class({
    Implements: Events,
    initialize: function(element){
        // ...
    },
    complete: function(){
        this.fireEvent('complete');
    }
});

Above, Implements adds some methods to class.

There are lots of mixin way of doing this on the net. But in the end I feel confused. Why we do not simply extend an Events class but use a more complicated mixin application.

I am looking for something dry and simple to reuse. Like this one;

class BaseAnimal {
  //...
}


/* Events Mixin */
var Events={
   //...
}

/* Options Mixin */
var Options={
   //...
}

/* Extend base and add mixins */
class Parrot extends myMixinFuction(BaseAnimal,Events,Options){
   //...
}

/* No Base. Only add mixin */
 class Cat extends myMixinFuction(Events){
   //...
}

myMixinFuction function (...args){
  //do something that adds mixins to base class.
  //if no base create one empty class and add mixinis to it
  //return that Class
}
Zortext
  • 566
  • 8
  • 21
  • 2
    You could just Object.assign them onto the prototype.. eg.. `Object.assign(Widget.prototype, Events)` – Keith Sep 24 '18 at 15:06
  • Possible duplicate of [How to add mixins to ES6 javascript classes?](https://stackoverflow.com/questions/42247434/how-to-add-mixins-to-es6-javascript-classes) – str Sep 24 '18 at 15:07
  • ES6 classes offer you the extends keyword to inherit from a parent class. But this is restricted to 1 extension. You'll have to mess with assigning new properties to the prototypes if you want to inherit from multiple sources. – Shilly Sep 24 '18 at 15:07

1 Answers1

1

If you're looking for a simpler solution than mixins for Events, and you're working with DOM elements, you could consider just firing native DOM events

To attach an event listener

element.addEventListener("my:event", evt => myEventHandler(evt));

And instead of fireEvent

let evt = element.ownerDocument.createEvent('my:event');
evt.initEvent(eventtype, bubbles, cancelable);
evt.detail = detail;
let result = element.dispatchEvent(evt);

(bubbles and cancelable define how the event propagates through the DOM, and result will be 'true' unless your event listener invoked preventDefault)

unilynx
  • 456
  • 3
  • 10