-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvent.js
More file actions
94 lines (85 loc) · 2.46 KB
/
Event.js
File metadata and controls
94 lines (85 loc) · 2.46 KB
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
;(function (exports) {
'use strict'
/**
* @class Event A pub/sub management class.
*/
function Event() {
this._events = {}
}
var proto = Event.prototype
/**
* Add listener or listeners to the listeners array
* @param {String} evt Instance of event
*/
proto.on = function (evt) {
var args = Array.prototype.slice.call(arguments, 1)
// if (typeof evt !== 'function' || typeof evt !== 'object') {
// throw new Error('You can only listen an event with a function')
// }
if (!this._events.hasOwnProperty(evt)) {
this._events[evt] = []
}
Array.prototype.push.apply(this._events[evt], args)
}
/**
* Emit an event. You can pass an array as arguments
* and the callback function will be called with the arguments
* @param {String} evt
* @param {Array} args
*/
proto.trigger = function (evt, args) {
var args = Array.prototype.slice.call(arguments, 1)
var listeners = this._events[evt]
if (!this._events.hasOwnProperty(evt)) {
throw new Error('This event has not been listen')
}
for (var i = 0, length = listeners.length; i < length; i++) {
listeners[i].apply(this, args)
}
}
/**
* Remove an event From this._events.
* You can pass the function name to remove the function instead of remove the event
* @param {String} evt
* @returns Instance of Event
*/
proto.off = function (evt) {
var listeners = this._events,
args = Array.prototype.slice.call(arguments, 1)
if (!listeners.hasOwnProperty(evt)) {
throw new Error('You have not listen this event')
}
/* 这里打算删除指定的方法,但是没有indexOfFunction */
// args? listeners[evt].slice()
if (args !== undefined) {
var index = indexOfFunction(listeners[evt], args)
}
index === -1 ? delete listeners[evt] : listeners[evt].slice(index, index + 1)
return this
}
/**
* Get listenr's index in events
* @param {String} listeners
* @param {String} evt
* @returns {number} Index of the listeners
*/
function indexOfFunction(listeners, evt) {
for (var i = 0, length = listeners.length; i < length; i++) {
if (evt === listeners[i]) {
return i
}
}
return -1
}
if (typeof define === 'function' && define.amd) {
define(function () {
return Event;
});
}
else if (typeof module === 'object' && module.exports) {
module.exports = Event;
}
else {
window.Event = Event;
}
}(window || {}))