-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvp-pubsub.js
387 lines (384 loc) · 15.6 KB
/
vp-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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*Copyright 2014 Schuberg Philis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* globals bootstrap, ses */
(function (vpPubsub) {
/* jshint strict: false*/
// Montage Require
if (typeof bootstrap === 'function') {
bootstrap('promise', vpPubsub);
// CommonJS & nodejs
} else if (typeof exports === 'object') {
module.exports = vpPubsub();
// RequireJS
} else if (typeof define === 'function' && define.amd) {
define(vpPubsub);
// SES (Secure EcmaScript)
} else if (typeof ses !== 'undefined') {
if (!ses.ok()) {
return;
} else {
ses.makeVPpubsub = vpPubsub;
}
// <script>
} else {
window.VPpubsub = vpPubsub();
}
})(function () {
/* jshint newcap: false */
'use strict';
var validSubscribe = /^!?(\*$|[a-z])([a-z0-9]*)(\.([a-z0-9]+|\*$))*(@[0-9a-z]+)?$/,
validPublish = /^[a-z]([a-z0-9]*)(\.[a-z0-9]+)*(@[0-9a-z]+)?$/,
async = (function () {
var api = typeof window === 'undefined' ? process : window,
next = api.requestAnimationFrame || api.webkitRequestAnimationFrame || api.mozRequestAnimationFrame || api.nextTick;
//browser
if (next) {
return next;
}
//fake async
return function (callback) {
setTimeout(callback, 1000 / 60);
};
}());
/**
* Array indexOf for IE8
* @param {Array} arr
* @param {*} needed
* @return {Number}
*/
function indexOf(arr, needed) {
if (arr.indexOf) {
return arr.indexOf(needed);
}
for (var i = 0, max = arr.length; i < max; i++) {
if (arr[i] === needed) {
return i;
}
}
return -1;
}
/**
* isFunction the given object a function
* @param {*} obj to test
* @return {Boolean} returns true if given object is an function
*/
function isFunction (obj) {
return typeof obj === 'function';
}
/**
* VPpubsub module
*/
function VPpubsub () {
var subscribers = {},
published = {},
api;
return (api = {
/**
* Publish a event
* @param {string} evnt The event that you want to publish
* @param {*} [data] Data that you want to send along with the event
* @param {*} [scope] Event scope
* @param {boolean} [notAsync=false] Events are default asynchronous, but in some cases yo don't want that
*/
pub: function (evnt, data, scope, notAsync) {
var evntPart = '',
subs = [],
originEvent = evnt;
/**
* Adds the event to published events
* @param {String} evnt
*/
function addToPublished(evnt) {
var scopeIndex;
//add published
if (!published[evnt]) {
published[evnt] = {
scopes:[],
data: []
};
}
//get event scope index
scopeIndex = indexOf(published[evnt].scopes, scope);
if (!~scopeIndex) {
scopeIndex = published[evnt].scopes.push(scope) - 1;
}
//update / add last called data to event scope
published[evnt].data[scopeIndex] = data;
}
function callAsync(sub, thisArg, data, originEvent) {
async(function () {
if (sub.$$VPpubsubRemoved !== originEvent) {
sub.call(thisArg, data, originEvent, sub);
}
});
}
//is event valid
if (validPublish.test(evnt)) {
//subscriber with id
if (subscribers[evnt]) {
subs = subs.concat(subscribers[evnt]);
}
//remove event
evnt = evnt.split('@')[0];
//subscriber without id
if (evnt !== originEvent && subscribers[evnt]) {
subs = subs.concat(subscribers[evnt]);
}
//add to published
addToPublished(evnt);
//wild card
if (subscribers[evnt + '.*']) {
subs = subs.concat(subscribers[evnt + '.*']);
}
//all other levels
evnt = evnt.split('.');
evntPart = evnt[0];
for (var i = 1, max = evnt.length; i < max; i++) {
if (subscribers[evntPart + '.*']) {
subs = subs.concat(subscribers[evntPart + '.*']);
}
evntPart += '.' + evnt[i];
}
//all
if (subscribers['*']) {
subs = subs.concat(subscribers['*']);
}
//start publishing
for (var x = 0, xmax = subs.length; x < xmax; x++) {
if (!subs[x][1] || subs[x][1] === scope) {
if (notAsync) {
subs[x][0].call(subs[x][2], data, originEvent, subs[x][0]);
} else {
callAsync(subs[x][0], subs[x][2], data, originEvent);
}
}
}
}
},
/**
* Subscribe to a event
* valid subscribe events
* 'x' or 'somelongname' or 'a123' the first character of a event must be a-z, a event must only contain only small characters or numbers
* 'x.x' you can use a '.' to name space the event
* 'x.*' you can use a '*' to subscribe to all events in a name space
* '*' subscribe to all events
* invalid subscribe events
* '1a' the first character can't be a number
* 'a.' name space can't be empty
* 'a#$' a event can't have other characters than a-z or 0-9
* Explanation mark "!" will republish the event to this subscriber if the event was already publish before
* @param {string} evnt The event where you want to subscribe
* @param {Function} subscriber The subscriber to the events
* @param {*} [scope] Scope can be used to only subscribe to events that are in that scope
* @param {*} [thisArg] The `this` scope of the subscriber
*/
sub: function (evnt, subscriber, scope, thisArg) {
var allEvnt = evnt.split('|'),
parseEvnt, pubIndex, isPublished;
/**
* Publish event to current subscriber, if force publish is used
* @param {String} evnt [description]
* @param {Function} sub [description]
*/
function publish (evnt, sub) {
var index = -1,
orgEvent = evnt;
//if the sub don't have
if (!~evnt.indexOf('*')) {
//check of event already is published for this scope
if (published[evnt]) {
index = indexOf(published[evnt].scopes, scope);
}
} else {
//rewrite event to regex
evnt = new RegExp('^' +
evnt.substr(0, evnt.length - 2)
.replace('.', '\\.') +
'(?![a-zA-Z0-9])');
//find event based on regex
for (orgEvent in published) {
if (evnt.test(orgEvent)) {
index = indexOf(published[orgEvent].scopes, scope);
break;
}
}
}
//do we've found a event ?
if (~index) {
//call subscriber
sub.call(thisArg, published[orgEvent].data[index], orgEvent, sub);
}
}
//check of subscriber is a function
if (!isFunction(subscriber)) {
return;
}
//loop though all events
for (var i = 0, max = allEvnt.length; i < max; i++) {
parseEvnt = allEvnt[i];
isPublished = false;
if (validSubscribe.test(allEvnt[i])) {
//fore publish if published to this subscriber
if (parseEvnt.slice(0, 1) === '!') {
parseEvnt = parseEvnt.slice(1);
isPublished = true;
}
//add subscriber list
if (!subscribers[parseEvnt]) {
subscribers[parseEvnt] = [];
}
delete subscriber.$$VPpubsubRemoved;
//add subscriber
pubIndex = subscribers[parseEvnt].push([
subscriber,
scope,
thisArg
]);
//is published check
if (isPublished) {
publish(parseEvnt, subscribers[parseEvnt][pubIndex - 1][0]);
}
}
}
},
/**
* Subscribe once to an event
* @param {String} evnt you can't subscribe to a channel ( * )
* @param {Function} subscriber
* @param {*} scope
* @param {*} thisArg
*/
subonce: function (evnt, subscriber, scope, thisArg) {
//check of subscriber is a function
if (!isFunction(subscriber)) {
return;
}
//you can't use *
if (!~evnt.indexOf('*')) {
api.sub(evnt, function (data, evnt, $$sub) {
api.unsub(evnt, $$sub, scope);
subscriber.call(thisArg, data, evnt, subscriber);
}, scope, thisArg);
}
},
/**
* Subscribe to a event via promise like API
* @param {string} evnt The event where you want to subscribe
* @param {*} [scope] Scope can be used to only subscribe to events that are in that scope
* @param {*} [thisArg] The `this` scope of the subscriber
* @return {Object} thenable object.
*/
on: function (evnt, scope, thisArg) {
var value,
callbacks = [],
called, once;
/**
* unsubscribe
*/
function unsub () {
api.unsub(evnt, sub, scope, thisArg)
}
/**
* then
*/
function then () {
var max = callbacks.length;
//check of it should only run only once
if (called && once) {
return;
}
//check of we have data to call all callbacks
if (max && value) {
//loop though all callbacks
for (var i = 0; i < max; i++) {
callbacks[i].apply(thisArg, value);
}
//set called
called = true;
//if run only once unsub
if (once) {
unsub();
}
}
}
/**
* Subscribe
* @param {*} data
* @param {String} evnt
* @param {Function} $$sub
* @see VPpubsub.sub
*/
function sub (data, evnt, $$sub) {
value = [data, evnt, $$sub];
then();
}
//sub
api.sub(evnt, sub, scope, thisArg);
//add off method to the promise
return {
/**
* Unsubscribe to the current event
*/
off: unsub,
/**
* then will run fulfill when the event is publish
* @param {Function} fulfill function that should run after the event is publish
*/
then: function (fulfill) {
//check of fullfill is a function
if (isFunction(fulfill)) {
//push in callback queue
callbacks.push(fulfill);
}
//run then
then();
//return off
return {
off: function () {
once = true;
if (called) {
unsub();
}
}
};
}
}
},
/**
* Unsubscribe a subscriber from a event
* @param {string} evnt Event where from you want to unsubscribe
* @param {Function} subscriber the subscriber
* @param {*} [scope] the scope if used by subscribing
*/
unsub: function (evnt, subscriber, scope) {
var eventSubs = subscribers[evnt] || [];
//check of subscriber is a function
if (!isFunction(subscriber)) {
return;
}
for (var i = 0, max = eventSubs.length; i < max; i++) {
if (eventSubs[i][0] === subscriber && (!eventSubs[i][1] || eventSubs[i][1] === scope)) {
subscriber.$$VPpubsubRemoved = evnt;
eventSubs.splice(i, 1);
//index changed
i--;
max--;
}
}
},
fork: function () {
return VPpubsub();
}
});
}
return VPpubsub();
});