-
Notifications
You must be signed in to change notification settings - Fork 17
/
asevented.js
105 lines (90 loc) · 2.7 KB
/
asevented.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
98
99
100
101
102
103
104
105
/**
* asEvented v0.4.6 - an event emitter mixin which provides the observer pattern to JavaScript object.
*
* Copyright 2015, Michal Kuklis
* Dual licensed under the MIT or GPL Version 2 licenses.
*
**/
(function (name, global, definition) {
if (typeof module !== 'undefined') {
module.exports = definition();
} else if (typeof define === 'function' && define.amd) {
define(definition);
} else {
global[name] = definition();
}
})('asEvented', this, function () {
return (function () {
var ArrayProto = Array.prototype;
var nativeIndexOf = ArrayProto.indexOf;
var slice = ArrayProto.slice;
function bind(event, fn) {
var i, part;
var events = this.events = this.events || {};
var parts = event.split(/\s+/);
var num = parts.length;
for (i = 0; i < num; i++) {
events[(part = parts[i])] = events[part] || [];
if (_indexOf(events[part], fn) === -1) {
events[part].push(fn);
}
}
return this;
}
function one(event, fn) {
// [notice] The value of fn and fn1 is not equivalent in the case of the following MSIE.
// var fn = function fn1 () { alert(fn === fn1) } ie.<9 false
var fnc = function () {
this.unbind(event, fnc);
fn.apply(this, slice.call(arguments));
};
this.bind(event, fnc);
return this;
}
function unbind(event, fn) {
var eventName, i, index, num, parts;
var events = this.events;
if (!events) return this;
parts = event.split(/\s+/);
for (i = 0, num = parts.length; i < num; i++) {
if ((eventName = parts[i]) in events !== false) {
index = (fn) ? _indexOf(events[eventName], fn) : -1;
if (index !== -1) {
events[eventName].splice(index, 1);
}
}
}
return this;
}
function trigger(event) {
var args, i;
var events = this.events, handlers;
if (!events || event in events === false) return this;
args = slice.call(arguments, 1);
handlers = events[event];
for (i = 0; i < handlers.length; i++) {
handlers[i].apply(this, args);
}
return this;
}
function _indexOf(array, needle) {
var i, l;
if (nativeIndexOf && array.indexOf === nativeIndexOf) {
return array.indexOf(needle);
}
for (i = 0, l = array.length; i < l; i++) {
if (array[i] === needle) {
return i;
}
}
return -1;
}
return function () {
this.bind = this.on = bind;
this.unbind = this.off = this.removeListener = unbind;
this.trigger = this.emit = trigger;
this.one = this.once = one;
return this;
};
})();
});