js-mixin
v2024.5.4
Published
A simple mixin library.
Downloads
6
Readme
JS Mixin
A TypeScript mixin library that allows you to enhance functions and objects with additional functionality.
Installation
To install the package, run:
npm install js-mixin
Usage
Importing the Mixin Class
First, import the Mixin
class (and the MixinType
type definition if you're using TypeScript) from the library:
import { Mixin, MixinType } from 'js-mixin';
Creating Mixins
Define your mixins as objects with methods that wrap the original methods. Here is one example mixin:
const LoggerMixin: MixinType = {
applyMixin: function (originalMethod: Function, ...args: any[]) {
console.log(originalMethod, `is performing an action.`, args);
return originalMethod(...args);
},
attack: function (originalMethod: Function, ...args: any[]) {
console.log(`The player is performing an action.`, args);
return originalMethod(...args);
}
};
Using Mixins with Standalone Functions
You can enhance standalone functions using the Mixin.apply
method:
/**
* Says hello to the specified name.
* @param name - The name to greet.
*/
function sayHello(name: string) {
console.log(`Hello, ${name}!`);
}
// Apply mixins to the standalone function
const enhancedSayHello = Mixin.apply(sayHello, LoggerMixin);
// Use the extended function
enhancedSayHello("World");
Using Mixins with Objects
You can also enhance methods of objects:
const player = {
name: 'Player1',
health: 100,
/**
* Attacks the specified target.
* @param target - The target to attack.
*/
attack: function (target: string) {
console.log(`${this.name} attacks ${target}!`);
}
};
Mixin.apply(player, LoggerMixin);
// Use the extended object
player.attack("Enemy");
Building the Library
To build the library, run:
npm run build
This will compile the TypeScript files in the src
directory and output the JavaScript files to the dist
directory.
Contributing
Contributions are welcome! Feel free to open an issue or submit a pull request.
License
This project is licensed under the MIT License. See the LICENSE file for details.