-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
98 lines (82 loc) · 2.39 KB
/
events.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
/**
* Copyright (c) 2023 Rhyme Digital LLC (https://rhyme.digital)
*
* @license LGPL-3.0-or-later
*/
//Namespace
var Rhyme = window.Rhyme || {};
//Encapsulate
(function ($) {
let self;
Rhyme.Events = {
//Properties
eventSubscribers: {}, //The callbacks that have been registered
env: 'dev',
/*
* Register the service
*/
init: function(options){
self = this;
self.options = options || {};
self.env = self.options.env ? self.options.env : 'dev';
return self;
},
/*
* Subscribe to a service
*
* @param string event
* @param function callback
* @param function bindTo
*/
subscribe: function(event, callback, bindTo) {
let uid = Rhyme.Util.getUniqueId();
self.eventSubscribers[event] = self.eventSubscribers[event] || {};
self.eventSubscribers[event][uid] = {'callback': callback, 'bindTo': bindTo};
return uid;
},
/*
* Unsubscribe from a service
*
* @param string event
* @param string key
*/
unsubscribe: function(event, key) {
try {
delete self.eventSubscribers[event][key];
} catch (e) {
self.log(e, 'error removing callback for event '+event+'... ');
}
},
/*
* Fire an event
*
* @param string event
* @param object data
*/
fire: function(event, data) {
if (!self.eventSubscribers[event]) return;
jQuery.each(self.eventSubscribers[event], function(key, val){
let caller = val;
try {
caller.callback(data, caller.bindTo);
} catch (e) {
self.log(e, 'error executing callback '+event+'... ');
}
});
},
/*
* Log a message
* @param {object|string|int} data
* @param {object|string|int} data
*/
log: function(e, data) {
if(self.env === 'dev') {
console.log(data);
console.log(e);
}
}
};
$(document).ready(function() {
Rhyme.Events.init(); //Todo - update in production
});
})(jQuery);