Skip to content

Commit 70dcbcc

Browse files
committed
Added hook.before / hook.after for convenient function wrapping.
1 parent 049e9cc commit 70dcbcc

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/utils.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,41 @@ var quoteRegExp = function(str) {
1010
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
1111
};
1212

13+
var hook = {};
14+
15+
/**
16+
* Wraps `method` on `self` so that `fn`
17+
* is invoked before the original method.
18+
*
19+
* @param {object} self
20+
* @param {string} method
21+
* @param {function} fn
22+
*/
23+
hook.before = function(self, method, fn) {
24+
var original = self[method];
25+
self[method] = function() {
26+
fn.apply(self, arguments);
27+
return original.apply(self, arguments);
28+
};
29+
};
30+
31+
/**
32+
* Wraps `method` on `self` so that `fn`
33+
* is invoked after the original method.
34+
*
35+
* @param {object} self
36+
* @param {string} method
37+
* @param {function} fn
38+
*/
39+
hook.after = function(self, method, fn) {
40+
var original = self[method];
41+
self[method] = function() {
42+
var result = original.apply(self, arguments);
43+
fn.apply(self, arguments);
44+
return result;
45+
};
46+
};
47+
1348
var once = function(fn) {
1449
var called = false;
1550
return function() {

0 commit comments

Comments
 (0)