mixin.js 900 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. class Mixin {
  3. constructor(host) {
  4. const originalMethods = {};
  5. const overriddenMethods = this._getOverriddenMethods(this, originalMethods);
  6. for (const key of Object.keys(overriddenMethods)) {
  7. if (typeof overriddenMethods[key] === 'function') {
  8. originalMethods[key] = host[key];
  9. host[key] = overriddenMethods[key];
  10. }
  11. }
  12. }
  13. _getOverriddenMethods() {
  14. throw new Error('Not implemented');
  15. }
  16. }
  17. Mixin.install = function(host, Ctor, opts) {
  18. if (!host.__mixins) {
  19. host.__mixins = [];
  20. }
  21. for (let i = 0; i < host.__mixins.length; i++) {
  22. if (host.__mixins[i].constructor === Ctor) {
  23. return host.__mixins[i];
  24. }
  25. }
  26. const mixin = new Ctor(host, opts);
  27. host.__mixins.push(mixin);
  28. return mixin;
  29. };
  30. module.exports = Mixin;