-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub-pattern.js
48 lines (39 loc) · 940 Bytes
/
pubsub-pattern.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
(function () {
'use strict';
var pubsub = (function pubsub () {
var subscribers = {};
function EventObject() {}
EventObject.prototype = {};
EventObject.prototype.constructor = EventObject;
function subscribe(event, callback) {
if(!subscribers[event]) {
var subscriberArray = [callback];
subscribers[event] = subscriberArray;
} else {
subscribers.push(callback);
}
}
function publish(event, data) {
var eventObject = new EventObject();
eventObject.type = event;
if(data) {
eventObject.data = data;
}
if (subscribers[event]) {
subscribers[event].forEach(function (callback) {
callback(eventObject);
});
}
}
return {
pub: publish,
sub: subscribe
}
}());
pubsub.sub('someCustomEvent', function(e) {
console.log('someCustomEvent was triggered! ', e.data.customData);
});
pubsub.pub('someCustomEvent', {
customData: 'customData!'
});
}());