-
Notifications
You must be signed in to change notification settings - Fork 25
/
pubsub.js
329 lines (287 loc) · 9.78 KB
/
pubsub.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
(function(scope) {
'use strict';
var pubsubInstance = null;
var pubsubConfig = null;
if(typeof pubsub === 'object') {
pubsubConfig = pubsub;
//node.js config from global
} else if(typeof global === 'object' && typeof global.pubsubConfig === 'object') {
pubsubConfig = global.pubsubConfig;
}
function Pubsub(config) {
var _eventObject = {};
var options = {
separator : (config && config.separator) ? config.separator : '/',
recurrent : (config && typeof config.recurrent === 'boolean') ? config.recurrent : (false),
depth : (config && typeof config.depth === 'number') ? config.depth : null,
async : (config && typeof config.async === 'boolean') ? config.async : (false),
context : (config && config.context) ? config.context : null,
log : (config && config.log) ? config.log : (false)
};
function forEach(dataArray, callback) {
var i = 0,
arrayLength = dataArray.length;
for(i = 0; i < arrayLength; i++) {
callback(i, dataArray[i]);
}
}
function isArray (obj) {
return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) === '[object Array]';
}
function executeCallback(subscriptions, args, async) {
async = (typeof async === 'boolean') ? async : options.async;
if(!subscriptions.length) {
return;
}
// clone array - callbacks can unsubscribe other subscriptions
// reduces a lot performance but is safe
var executedSubscriptions = subscriptions.slice();
forEach(executedSubscriptions, function(subscriptionId, subscription) {
if(typeof subscription === 'object' && executedSubscriptions.hasOwnProperty(subscriptionId)) {
if(async) {
setTimeout(function() {
subscription.callback.apply(subscription.context, args);
}, 4);
} else {
subscription.callback.apply(subscription.context, args);
}
}
});
}
function executePublishWildcard(nsObject, args) {
var nsElement;
for(nsElement in nsObject) {
if(nsElement[0] !== '_' && nsObject.hasOwnProperty(nsElement)) {
executeCallback(nsObject[nsElement]._events, args);
}
}
}
function publish(nsObject, args, parts, params) {
// work on copy - not on reference
parts = parts.slice();
var iPart = parts.shift();
var depth = params.depth;
var async = params.async;
var partsLength = params.partsLength;
var recurrent = params.recurrent;
var partNumber = (partsLength - parts.length);
// parts is empty
if(!iPart) {
executeCallback(nsObject._events, args, async);
return;
}
// handle subscribe wildcard
if(typeof nsObject['*'] !== 'undefined') {
publish(nsObject['*'], args, parts, params);
}
// handle publish wildcard
if(iPart === '*') {
executePublishWildcard(nsObject, args, async);
}
// no namespace = leave publish
if(typeof nsObject[iPart] === "undefined") {
if(params.log) {
console.warn('There is no ' + params.nsString + ' subscription');
}
return;
}
nsObject = nsObject[iPart];
if(recurrent === true && typeof depth !== 'number') { //depth is not defined
executeCallback(nsObject._events, args, async);
if(parts.length === 0) {
return;
}
} else if(recurrent === true && typeof depth === 'number' && partNumber >= (partsLength - depth)) { //if depth is defined
executeCallback(nsObject._events, args, async);
}
publish(nsObject, args, parts, params);
}
function executeSubscribeWildcard(nsObject, args, params) {
var parts = params.parts;
var async = params.async;
var nextPart = null;
if(parts.length === 0) {
executeCallback(nsObject._events, args, async);
} else {
nextPart = parts.shift();
if(nsObject[nextPart]) {
executeSubscribeWildcard(nsObject[nextPart], args, {
parts : parts,
async : async,
nsString : params.nsString
});
}
}
}
function subscribe(nsString, callback, params) {
var parts = nsString.split(options.separator),
nsObject, //Namespace object to which we attach event
context = (params && typeof params.context !== 'undefined') ? params.context : options.context,
eventObject = null,
i = 0;
if(!context) {
context = callback;
}
//Iterating through _eventObject to find proper nsObject
nsObject = _eventObject;
for(i = 0; i < parts.length; i += 1) {
if(typeof nsObject[parts[i]] === "undefined") {
nsObject[parts[i]] = {};
nsObject[parts[i]]._events = [];
}
nsObject = nsObject[parts[i]];
}
eventObject = {
callback : callback,
context : context // "this" parameter in executed function
};
nsObject._events.push(eventObject);
return { namespace : parts.join(options.separator),
event : eventObject };
}
function unsubscribe(subscribeObject) {
if(subscribeObject === null || typeof subscribeObject === 'undefined') {
return null;
}
var nsString = subscribeObject.namespace,
eventObject = subscribeObject.event,
parts = nsString.split(options.separator),
nsObject,
i = 0;
//Iterating through _eventObject to find proper nsObject
nsObject = _eventObject;
for(i = 0; i < parts.length; i += 1) {
if(typeof nsObject[parts[i]] === "undefined") {
if(options.log) {
console.error('There is no ' + nsString + ' subscription');
}
return null;
}
nsObject = nsObject[parts[i]];
}
forEach(nsObject._events, function(eventId) {
if(nsObject._events[eventId] === eventObject) {
nsObject._events.splice(eventId, 1);
}
});
}
return {
/**
* Publish event
* @param nsString string namespace string splited by dots
* @param args array of arguments given to callbacks
* @param params paramaters possible:
* @param recurrent bool should execution be bubbled throught namespace
* @param depth integer how many namespaces separated by dots will be executed
*/
publish : function(nsString, args, params) {
var parts = nsString.split(options.separator),
recurrent = (typeof params === 'object' && params.recurrent) ? params.recurrent : options.recurrent, // bubbles event throught namespace if true
depth = (typeof params === 'object' && params.depth) ? params.depth : options.depth,
async = (typeof params === 'object' && params.async) ? params.async : options.async,
partsLength = parts.length;
if(!parts.length) {
if(options.log) {
console.error('Wrong namespace provided ' + nsString);
}
return;
}
publish(_eventObject, args, parts, {
recurrent : recurrent,
depth : depth,
async : async,
parts : parts,
nsString : nsString,
partsLength : partsLength
});
},
/**
* Subscribe event
* @param nsString string namespace string splited by dots
* @param callback function function executed after publishing event
* @param params given params
* @param context object/nothing Optional object which will be used as "this" in callback
*/
subscribe : function(nsString, callback, params) {
var self = this,
subscriptions = [];
// array of callbacks - multiple subscription
if(isArray(callback)) {
forEach(callback, function(number) {
var oneCallback = callback[number];
subscriptions = subscriptions.concat(self.subscribe(nsString, oneCallback, params));
});
// array of namespaces - multiple subscription
} else if(isArray(nsString)) {
forEach(nsString, function(number) {
var namespace = nsString[number];
subscriptions = subscriptions.concat(self.subscribe(namespace, callback, params));
});
} else {
return subscribe.apply(self, arguments);
}
return subscriptions;
},
/**
* subscribeOnce event - subscribe once to some event, then unsubscribe immadiately
* @param nsString string namespace string splited by dots
* @param callback function function executed after publishing event
* @param params given params
* @param context object/nothing Optional object which will be used as "this" in callback
*/
subscribeOnce : function(nsString, callback, params) {
var self = this,
subscription = null;
function subscriptionCallback() {
var context = this;
callback.apply(context, arguments);
self.unsubscribe(subscription);
}
subscription = self.subscribe(nsString, subscriptionCallback, params);
return subscription;
},
/**
* Unsubscribe from given subscription
* @param subscribeObject subscription object given on subscribe (returned from subscription)
*/
unsubscribe : function(subscribeObject) {
var self = this;
//if we have array of callbacks - multiple subscription
if(isArray(subscribeObject)) {
forEach(subscribeObject, function(number) {
var oneSubscribtion = subscribeObject[number];
unsubscribe.apply(self, [oneSubscribtion]);
});
} else {
unsubscribe.apply(self, arguments);
}
},
/**
* newInstance - makes new instance of pubsub object with its own config
* @param params instance configuration
* @param separator separator (default is "/")
* @param recurrent should publish events be bubbled through namespace
* @param async should publish events be asynchronous - not blocking function execution
* @param log console.warn/error every problem
*/
newInstance : function(params) {
return new Pubsub(params);
}
}; //return block
}
pubsubInstance = new Pubsub(pubsubConfig);
//if sbd's using requirejs library to load pubsub.js
if(typeof define === 'function') {
define(pubsubInstance);
}
//node.js
if(typeof module === 'object' && module.exports) {
module.exports = pubsubInstance;
}
if(typeof window === 'object') {
window.pubsub = pubsubInstance;
if(window !== scope) {
scope.pubsub = pubsubInstance;
}
}
})(this);