1.0.1 • Published 7 years ago

es6-trait-implementer v1.0.1

Weekly downloads
1
License
ISC
Repository
-
Last release
7 years ago

ES6 Trait Implementer

This is a very easy to use, lightweight library that implements class traits, much like PHP's traits.

Install

Install via npm: npm i --save es6-trait-implementer

Usage

The library works by calling a function on a class before you use it, similar to how Higher-order-components (HOCs) work in React.

Main Class

This would be your class that you want to implement traits on, see below to see how to define traits.

import implementsTraits from 'es6-trait-implementer'; // Import the library first
import { GreetingTrait } from '...'; // Import your traits

// Have a class you want to use traits on
class MyClass {
    constructor () {
        this.greet();
    }
}

// Call the libraries function on the class with an array of traits
MyClass = implementsTraits(MyClass, [GreetingTrait]);

// Then use your class!
const myClass = new MyClass(); // Logs 'Hello, world!' to console

Trait Example

Traits are simply classes:

class GreetingTrait {
    greet () {
        console.log('Hello, world!');
    }
}

export { GreetingTrait }; // Don't forget to export!

Done!

Of course, you can export/import anyway you like, i.e export default class Trait { } with import Trait from '...' works fine, too.

Notes

Feel free to open up issues/pull requests if you find any problems.