magic-hook

2018-10-12 admin

magic-hook是什么

什么是magic-hook,Extends functions with pre hooks.

magic-hook使用教程帮助文档

magic-hook

Extends functions with pre hooks.

Build Status Coverage Status npm version

Installation

npm i -S magic-hook

Usage

You can add pre hooks to extend your methods.

'use strict'
var hook = require('magic-hook')

// The target function
function concat(a, b) {
  return a + b
}

// The hooked function
var hookedConcat = hook(concat)

// A pre hook
var msgNo = 0
function counterHook(next, a, b) {
  return next('concatenation #' + (++msgNo) + ': ' + a, b)
}
hookedConcat.pre(counterHook)

for (var i = 3; i--;) console.log(hookedConcat('Hello ', 'world!'))
//> concatenation #1: Hello world!
//> concatenation #2: Hello world!
//> concatenation #3: Hello world!

Hooks can be removed using removePre:

hookedConcat.removePre(counterHook)

console.log(hookedConcat('Hello ', 'world!'))
//> Hello world!

To remove all pres associated with a hook just call removePre with no arguments:

hookedConcat.removePre()

To abort the target function’s execution just don’t call the next function in the pre hook:

hookedConcat.pre(function(next) {
  return 'The original function was overwritten';
})

console.log(hookedConcat("Doesn't matter what goes here"))
//> The original function was overwritten

You can overwrite the target function’s result as well:

var hookedSum = hook(function(a, b) { return a + b; })

hookedSum.pre(function(sum, a, b) {
  if (a === 1 && b === 1) return 3

  return sum(a, b)
})

console.log(hookedSum(2, 2))
//> 4

console.log(hookedSum(1, 1))
//> 3

Motivation

Suppose you have an object with a save method.

It would be nice to be able to declare code that runs before save. For example, you might want to run validation code before every save. Or you might want to create plugins that will modify the input parameters of your save method.

License

MIT © Zoltan Kochan

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-42521.html

文章标题:magic-hook

回到顶部