-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
55 lines (47 loc) · 1.35 KB
/
index.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
'use strict';
var ftw = typeof window !== 'undefined' ? window : {}
, once = require('one-time');
/**
* Uniform handling for event listening and removing.
*
* @param {Mixed} what The thing we need to listen upon.
* @param {String} when Name of the event we need to listen on.
* @param {Function} how Function to be executed.
* @returns {Function}
* @api public
*
* @example ```js
// listen for `stream` to 'end'
var stop = hearing(stream, 'end', callback);
// stop listening after 1 second
setTimeout(stop, 1000);
```
*/
module.exports = function hearing(what, when, how) {
if ('addEventListener' in what) {
what.addEventListener(when, how, false);
return once(function aid() {
what.removeEventListener(when, how, false);
});
}
if ('attachEvent' in what) {
//
// Use a small wrapper so we can force window.event for those cases when the
// supplied event is missing (old browsers).
//
var wrapper = function wrapper(e) {
how.call(this, e || ftw.event);
};
what.attachEvent('on'+ when, wrapper);
return once(function aid() {
what.detachEvent('on'+ when, wrapper);
});
}
if ('on' in what) {
what.on(when, how);
return once(function aid() {
if ('removeListener' in what) what.removeListener(when, how);
else if ('off' in what) what.off(when, how);
});
}
};