1

Is it possible to extend Ember class on condition? Something like this:

A.reopen({
  if (condition) {
    init: function() {
      this.super();
      // some functionality
    }.on('didInsertElement');
  }
})

Currently I have such pattern:

A.reopen({
  init: function() {
    this.super();
    if (condition) {
      // some stuff
    }
  }.on('didInsertElement'),

  cleanup: function() {
    if (condition) {
      // some stuff
    }
  }.on('willDestroyElement')
})

I guessed if I can extend A class on condition I can simplify my pattern like this:

A.reopen({
  if (condition) {
    init: function() {
      this.super();
      // some functionality
    }.on('didInsertElement'),

    clear_up: function() {
      // some stuff
    }.on('willDestroyElement')
  }
})

All class extensions made in the plugin for discourse

megas
  • 21,401
  • 12
  • 79
  • 130

1 Answers1

0

It looks like you want what in Java would be called an abstract class.

Ember.Component.extend({ // abstract class

  doSomeInit: Ember.K,

  doSomeCleaning: Ember.K,

  didInsertElement: function() {
    this.super(..arguments);
    this.doSomeInit();
  },

  willDestroyElement: function() {
    this.doSomeCleaning();
  }
})

// class A
Ember.Component.extend(MyIncompleteClass, {

  doSomeInit: function() { /* etc */ },

  doSomeCleaning: function() { /* etc */ }

});

// class B
Ember.Component.extend(MyIncompleteClass, {

  doSomeInit: function() { /* etc */ },

  doSomeCleaning: function() { /* etc */ }

});

Sidenote: Is best to override the lifecycle hooks than to use Ember.on, to guarantee order of execution; that is in the case of multiple Ember.on for the same event.

givanse
  • 14,503
  • 8
  • 51
  • 75
  • 1
    I'm extending ember classes from plugin, I can't create my own classes even abstract – megas Oct 23 '16 at 21:16
  • mind updating your question with that bit? how are you extending from the plugin? (ember cli addon, I assume) – givanse Oct 23 '16 at 22:31