forked from aheckmann/jquery.hook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.hook.js
80 lines (70 loc) · 2.22 KB
/
jquery.hook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*!
* jQuery.hook v1.0
*
* Copyright (c) 2009 Aaron Heckmann, contributions (c) 2011 Jason Featheringham
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
/**
* Provides the ability to hook into any jQuery.fn[method]
* with onbeforeMETHOD, onMETHOD, and onafterMETHOD.
*
* Pass in a string or array of method names you want
* to hook with onbefore, on, or onafter. If the handler
* for onbefore or on returns false, all future events
* are cancelled
*
* Example:
* jQuery.hook('show');
* jQuery(selector).bind('onbeforeshow', function (e) { alert(e.type);});
* jQuery(selector).show() -> alerts 'onbeforeshow'
*
* jQuery.hook(['show','hide']);
* jQuery(selector)
* .bind('onbeforeshow', function (e) { alert(e.type);})
* .bind('onshow', function (e) { alert(e.type);})
* .bind('onaftershow', function (e) { alert(e.type);})
* .bind('onafterhide', function (e) { alert("The element is now hidden.");});
* jQuery(selector).show().hide()
* -> alerts 'onbeforeshow' then alerts 'onshow', then alerts 'onaftershow',
* then after the element is hidden alerts 'The element is now hidden.'
*
*
* You can also unhook what you've hooked into by calling jQuery.unhook() passing
* in your string or array of method names to unhook.
*
*/
;(function($){
$.hook = function (fns) {
fns = typeof fns === 'string' ?
fns.split(' ') :
$.makeArray(fns)
;
jQuery.each( fns, function (i, method) {
var old = $.fn[ method ];
if ( old && !old.__hookold ) {
$.fn[ method ] = function () {
if ( this.triggerHandler('onbefore'+method) === false ) { return; }
if ( this.triggerHandler('on'+method) === false ) { return; }
var ret = old.apply(this, arguments);
this.triggerHandler('onafter'+method);
return ret;
};
$.fn[ method ].__hookold = old;
}
});
};
$.unhook = function (fns) {
fns = typeof fns === 'string' ?
fns.split(' ') :
$.makeArray(fns)
;
jQuery.each( $.makeArray(fns), function (i, method) {
var cur = $.fn[ method ];
if ( cur && cur.__hookold ) {
$.fn[ method ] = cur.__hookold;
}
});
};
})(jQuery);