1 | /*!
|
2 | * hookable
|
3 | * Copyright(c) 2012 RGBboy <me@rgbboy.com>
|
4 | * MIT Licensed
|
5 | */
|
6 |
|
7 | /**
|
8 | * Module Dependencies
|
9 | */
|
10 |
|
11 |
|
12 |
|
13 | /**
|
14 | * Add hookable functionality to component instance.
|
15 | *
|
16 | * @param {Object} that
|
17 | * @api public
|
18 | */
|
19 | exports = module.exports = function (that) {
|
20 |
|
21 | var beforeHooks = {},
|
22 | afterHooks = {};
|
23 |
|
24 | /**
|
25 | * .hook
|
26 | *
|
27 | * @todo: make this work async with callback
|
28 | *
|
29 | * @param {String} name
|
30 | * @param {Function} function
|
31 | * @return {Function}
|
32 | * @api public
|
33 | */
|
34 | that.hook = function (name, fn) {
|
35 | return function () {
|
36 | var args = [].slice.call(arguments),
|
37 | context = this,
|
38 | i;
|
39 | // before
|
40 | if (beforeHooks[name] && beforeHooks[name].length > 0) {
|
41 | for (i = 0; i < beforeHooks[name].length; i += 1) {
|
42 | beforeHooks[name][i].apply(context, args); // make this work serial async
|
43 | };
|
44 | };
|
45 | // original
|
46 | fn.apply(context, args);
|
47 | // after
|
48 | if (afterHooks[name] && afterHooks[name].length > 0) {
|
49 | for (i = 0; i < afterHooks[name].length; i += 1) {
|
50 | afterHooks[name][i].apply(context, args); // make this work serial async
|
51 | };
|
52 | };
|
53 | };
|
54 | };
|
55 |
|
56 | /**
|
57 | * .before
|
58 | *
|
59 | * @param {String} name
|
60 | * @param {Function} function
|
61 | * @return {Object} that, chainable
|
62 | * @api public
|
63 | */
|
64 | that.before = function (name, fn) {
|
65 | beforeHooks[name] = beforeHooks[name] || [];
|
66 | beforeHooks[name].push(fn);
|
67 | return that;
|
68 | };
|
69 |
|
70 | /**
|
71 | * .after
|
72 | *
|
73 | * @param {String} name
|
74 | * @param {Function} function
|
75 | * @return {Object} that, chainable
|
76 | * @api public
|
77 | */
|
78 | that.after = function (name, fn) {
|
79 | afterHooks[name] = afterHooks[name] || [];
|
80 | afterHooks[name].push(fn);
|
81 | return that;
|
82 | };
|
83 |
|
84 | return that;
|
85 |
|
86 | };
|
87 |
|
88 | /**
|
89 | * Library version.
|
90 | */
|
91 |
|
92 | exports.version = '0.0.2'; |
\ | No newline at end of file |