Tutorial: README

README

Class with plugins

Class with plugins is an npm module that gives you a class with that allows you to extend its functionality using plugins that can expose properties on the class or run functions using 'hooks'

Installing

Run npm install

Testing

Run npm test

Usage

Extend the ClassWithPlugins class and call the hook function to allow plugins to hook into certain points in the code

import ClassWithPlugins from 'class-with-plugins';

class Model extends ClassWithPlugins {

  static get _type() {
    return 'Model';
  }

}

Write a plugin, this example clones a model and removes its id -, createdOn - and modifiedOn property

import _ from 'lodash';
import ClassWithPlugins from 'class-with-plugins';

// 'Model' refers to the static get _type on the class, 'clone' is the name of the plugin
ClassWithPlugins.registerPlugin('Model', 'clone', {

  // expose the 'clone' property on the Model
  expose: ['clone'],

  clone(model) {
    const clone = _.clone(model);

    delete clone[this.idKey];
    delete clone[this.modifiedOnKey];
    delete clone[this.createdOnKey];

    return clone;
  }

});

Now to have the plugin be present in you class, make sure it appears in the plugins property of the class (an array of strings)

class Model extends ClassWithPlugins {
  ...
  ...
  ...
}

Model.prototype.plugins = ['clone'];

or

class Model extends ClassWithPlugins {

  constructor(options = {}) {
    options.plugins = ['clone'];
    super(options);
  }

}

then, finally, to use the plugin

const model = new Model({...});
model.clone({id:3, name: 'bob'});
> {name: 'bob'}