-
Notifications
You must be signed in to change notification settings - Fork 0
/
fnd.evt.js
executable file
·97 lines (82 loc) · 2.5 KB
/
fnd.evt.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
(function (root, factory) {
'use strict';
/* global define, module, require */
if (typeof define === 'function' && define.amd) { // AMD
define(['./fnd'], factory);
} else if (typeof exports === 'object') { // Node, browserify and alike
module.exports = factory(require('./fnd'));
} else {
// Browser globals (root is window)
root.fnd.evt = factory(root.fnd);
}
}(this, function (fnd) {
'use strict';
/**
*
* @param {HTMLElement} element
* @param {string} eventName
* @param {function} handler
* @param {string} [selector]
* @returns {Function}
*/
function on (element, eventName, handler, selector) {
var boundHandler;
var useCapture;
if (selector) {
boundHandler = function (event) {
if (fnd.is(selector)(event.target)) {
handler(event);
}
};
useCapture = true;
} else {
boundHandler = handler;
useCapture = false;
}
element.addEventListener(eventName, boundHandler, useCapture);
return function () {
element.removeEventListener(eventName, boundHandler, useCapture);
};
}
function extractHandler (events, key, context) {
var handler = events[key];
if (handler instanceof Function) {
return handler;
} else if (typeof handler === 'string') {
if (context[handler]) {
return context[handler];
} else {
throw new Error('Invalid or missing context for "' + handler + '"');
}
}
}
var eventSplitter = /^(\S+)\s*(.*)$/;
function parseEvent (eventKey) {
return eventKey.split(eventSplitter);
}
function callableList () {
var list = [];
var result = function () {
for (var i = 0; i < list.length; i++) {
list[i]();
}
};
result.push = list.push.bind(list);
return result;
}
function evt (element, events, context) {
var unbinders = callableList();
Object.keys(events).forEach(function (eventKey) {
var parts = parseEvent(eventKey);
unbinders.push(on(
element,
parts[1],
extractHandler(events, eventKey, context).bind(context),
parts[2]
));
});
return unbinders;
}
evt.on = on;
return evt;
}));