JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 580
  • Score
    100M100P100Q98636F
  • License MIT

Patch / extend / wrap / hook into class methods in a type-safe way

Package Exports

  • patch-method

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (patch-method) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

patch-method

Build Status npm version Download Total code style: prettier dependencies devDependencies

This package allows you to patch class methods in a fully type-safe way. This is especially useful to create decorators that "mixin" methods.

patchMethod

Allows you to override any method on a given class. Enforces that the passed methodName actually is a method, and enforces that your hook fn has the same type signature as the original method.

The first argument to fn is a superMethod callback that is bound to the instance of the class. This way you can optionally call the original method implementation and also alter the arguments.

import patchMethod from 'patch-method';

class Foo {
  bar(value: number) {
    console.log(`Received: ${value}`);
    return number
  }
}

patchMethod(Foo, 'bar', function(superMethod, value) {
  console.log(`${this.constructor.name}#bar was called with ${value}.`)
  return superMethod(value + 1)
})

const foo = new Foo
foo.bar(10)
// => 'Foo#bar was called with 10.'
// => 'Received: 11'
// => 11

beforeMethod

Register a hook to be executed before the original method is run. Gets passed the original arguments the method was called with. The return value of the hook is ignored.

import { beforeMethod } from 'patch-method';

class Foo {
  bar(value: number) {
    return number
  }
}

beforeMethod(Foo, 'bar', function(value) {
  console.log(`${this.constructor.name}#bar was called with ${value}.`)
})

const foo = new Foo
foo.bar(10)
// => 'Foo#bar was called with 10.'
// => 'Received: 10'
// => 10

afterMethod

Register a hook to be executed right after the original method is run. Gets passed the original arguments the method was called with. Also gets passed the return value of the method as the first parameter. The return value of the hook is ignored.

import { afterMethod } from 'patch-method';

class Foo {
  bar(value: number) {
    return number
  }
}

afterMethod(Foo, 'bar', function(returnValue, value) {
  console.log(`${this.constructor.name}#bar was called with ${value}.`)
})

const foo = new Foo
foo.bar(10)
// => 'Received: 10'
// => 'Foo#bar was called with 10.'
// => 10