-1

I hva been examining the source code of konvajs (https://github.com/konvajs/konva) and i am fascinated by the design pattern, eg. src/shape.js (https://github.com/konvajs/konva/blob/master/src/Shape.js):

    Konva.Shape = function(config) {
      this.__init(config);
    };

    Konva.Util.addMethods(Konva.Shape, {
    __init: function(config) {
    this.nodeType = 'Shape';
    \\ more code

Here it seems that the constructor of the class Shape passes the argument 'config' to the __init method not declared yet. Also the __init method is added to the class by the Util method addMethods. To me this seems like a flexible way of coding, that is if you want to add some new feature a utility class handles it for you.

Moreover, the default values for defining attributes is added by a factory class (eg. see the bottom part of shape.js).

So my question is:

Is it possible to implement a similar design pattern in typescript? Or is this design pattern not applicable in OOP-languages (or what ever typescript is).

1 Answers1

0

If you are going to call method in a constructor, then you should add method to class declaration. How it would be, if sometime you will forget to call required addMethod util?

Anyway, if you really need to add methods to class dynamicly (I can't imagine why), you can use something like this:

interface IInitializable {
    __init?(config);
}
function addInitializer<T>(obj: T, init): T & IInitializable {
    let initializable = obj as T & IInitializable;
    initializable.__init = init;
    return initializable;
}

class Shape {
    foo() {            
    }
}

function init(shape: IInitializable) {
    shape.__init("Hello there");
}
let shape = new Shape();
let initializableShape = addInitializer(shape, 
    function (config) {
        alert(config)
    });;
init(initializableShape);

Also, you can use TypeScript mixins.

Pavel
  • 2,602
  • 1
  • 27
  • 34