-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediator.js
415 lines (325 loc) · 13.6 KB
/
mediator.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
(function (undefined) {
// Prevent exporting Node.js/CommonJS/AMD module
var exports = undefined,
define = undefined;
// Juggling with 'this' keyword
var MediatorClass = (new ns).Mediator;
// Expose class (https://github.com/ajacksified/Mediator.js/issues/40)
MediatorClass.prototype.constructor = MediatorClass;
// Export instance
Mediator = new MediatorClass;
// Namespace wrapper (hoisted)
function ns() {
/*!
* Mediator.js Library v0.9.8
* https://github.com/ajacksified/Mediator.js
*
* Copyright 2013, Jack Lawson
* MIT Licensed (http://www.opensource.org/licenses/mit-license.php)
*
* For more information: http://thejacklawson.com/2011/06/mediators-for-modularized-asynchronous-programming-in-javascript/index.html
* Project on GitHub: https://github.com/ajacksified/Mediator.js
*
* Last update: October 19 2013
*/
(function(global, factory) {
'use strict';
if(typeof define === 'function' && define.amd) {
// AMD
define('mediator-js', [], function() {
global.Mediator = factory();
return global.Mediator;
});
} else if (typeof exports !== 'undefined') {
// Node/CommonJS
exports.Mediator = factory();
} else {
// Browser global
global.Mediator = factory();
}
}(this, function() {
'use strict';
// We'll generate guids for class instances for easy referencing later on.
// Subscriber instances will have an id that can be refernced for quick
// lookups.
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
// Subscribers are instances of Mediator Channel registrations. We generate
// an object instance so that it can be updated later on without having to
// unregister and re-register. Subscribers are constructed with a function
// to be called, options object, and context.
function Subscriber(fn, options, context){
if(!(this instanceof Subscriber)) {
return new Subscriber(fn, options, context);
}
this.id = guidGenerator();
this.fn = fn;
this.options = options;
this.context = context;
this.channel = null;
}
Subscriber.prototype = {
// Mediator.update on a subscriber instance can update its function,context,
// or options object. It takes in an object and looks for fn, context, or
// options keys.
update: function(options){
if(options){
this.fn = options.fn || this.fn;
this.context = options.context || this.context;
this.options = options.options || this.options;
if(this.channel && this.options && this.options.priority !== undefined) {
this.channel.setPriority(this.id, this.options.priority);
}
}
}
};
function Channel(namespace, parent){
if(!(this instanceof Channel)) {
return new Channel(namespace);
}
this.namespace = namespace || "";
this._subscribers = [];
this._channels = {};
this._parent = parent;
this.stopped = false;
}
// A Mediator channel holds a list of sub-channels and subscribers to be fired
// when Mediator.publish is called on the Mediator instance. It also contains
// some methods to manipulate its lists of data; only setPriority and
// StopPropagation are meant to be used. The other methods should be accessed
// through the Mediator instance.
Channel.prototype = {
addSubscriber: function(fn, options, context){
var subscriber = new Subscriber(fn, options, context);
if(options && options.priority !== undefined){
// Cheap hack to either parse as an int or turn it into 0. Runs faster
// in many browsers than parseInt with the benefit that it won't
// return a NaN.
options.priority = options.priority >> 0;
if(options.priority < 0){ options.priority = 0; }
if(options.priority >= this._subscribers.length){ options.priority = this._subscribers.length-1; }
this._subscribers.splice(options.priority, 0, subscriber);
}else{
this._subscribers.push(subscriber);
}
subscriber.channel = this;
return subscriber;
},
// The channel instance is passed as an argument to the mediator subscriber,
// and further subscriber propagation can be called with
// channel.StopPropagation().
stopPropagation: function(){
this.stopped = true;
},
getSubscriber: function(identifier){
var x = 0,
y = this._subscribers.length;
for(x, y; x < y; x++){
if(this._subscribers[x].id === identifier || this._subscribers[x].fn === identifier){
return this._subscribers[x];
}
}
},
// Channel.setPriority is useful in updating the order in which Subscribers
// are called, and takes an identifier (subscriber id or named function) and
// an array index. It will not search recursively through subchannels.
setPriority: function(identifier, priority){
var oldIndex = 0,
x = 0,
sub, firstHalf, lastHalf, y;
for(x = 0, y = this._subscribers.length; x < y; x++){
if(this._subscribers[x].id === identifier || this._subscribers[x].fn === identifier){
break;
}
oldIndex ++;
}
sub = this._subscribers[oldIndex];
firstHalf = this._subscribers.slice(0, oldIndex);
lastHalf = this._subscribers.slice(oldIndex+1);
this._subscribers = firstHalf.concat(lastHalf);
this._subscribers.splice(priority, 0, sub);
},
addChannel: function(channel){
this._channels[channel] = new Channel((this.namespace ? this.namespace + ':' : '') + channel, this);
},
hasChannel: function(channel){
return this._channels.hasOwnProperty(channel);
},
returnChannel: function(channel){
return this._channels[channel];
},
removeSubscriber: function(identifier){
var x = this._subscribers.length - 1;
// If we don't pass in an id, we're clearing all
if(!identifier){
this._subscribers = [];
return;
}
// Going backwards makes splicing a whole lot easier.
for(x; x >= 0; x--) {
if(this._subscribers[x].fn === identifier || this._subscribers[x].id === identifier){
this._subscribers[x].channel = null;
this._subscribers.splice(x,1);
}
}
},
// This will publish arbitrary arguments to a subscriber and then to parent
// channels.
publish: function(data){
var x = 0,
y = this._subscribers.length,
shouldCall = false,
subscriber, l,
subsBefore,subsAfter;
// Priority is preserved in the _subscribers index.
for(x, y; x < y; x++) {
// By default set the flag to false
shouldCall = false;
subscriber = this._subscribers[x];
if(!this.stopped){
subsBefore = this._subscribers.length;
if(subscriber.options !== undefined && typeof subscriber.options.predicate === "function"){
if(subscriber.options.predicate.apply(subscriber.context, data)){
// The predicate matches, the callback function should be called
shouldCall = true;
}
}else{
// There is no predicate to match, the callback should always be called
shouldCall = true;
}
}
// Check if the callback should be called
if(shouldCall) {
// Check if the subscriber has options and if this include the calls options
if (subscriber.options && subscriber.options.calls !== undefined){
// Decrease the number of calls left by one
subscriber.options.calls--;
// Once the number of calls left reaches zero or less we need to remove the subscriber
if(subscriber.options.calls < 1){
this.removeSubscriber(subscriber.id);
}
}
// Now we call the callback, if this in turns publishes to the same channel it will no longer
// cause the callback to be called as we just removed it as a subscriber
subscriber.fn.apply(subscriber.context, data);
subsAfter = this._subscribers.length;
y = subsAfter;
if (subsAfter === subsBefore - 1){
x--;
}
}
}
if(this._parent){
this._parent.publish(data);
}
this.stopped = false;
}
};
function Mediator() {
if(!(this instanceof Mediator)) {
return new Mediator();
}
this._channels = new Channel('');
}
// A Mediator instance is the interface through which events are registered
// and removed from publish channels.
Mediator.prototype = {
// Returns a channel instance based on namespace, for example
// application:chat:message:received. If readOnly is true we
// will refrain from creating non existing channels.
getChannel: function(namespace, readOnly){
var channel = this._channels,
namespaceHierarchy = namespace.split(':'),
x = 0,
y = namespaceHierarchy.length;
if(namespace === ''){
return channel;
}
if(namespaceHierarchy.length > 0){
for(x, y; x < y; x++){
if(!channel.hasChannel(namespaceHierarchy[x])){
if (readOnly) {
break;
} else {
channel.addChannel(namespaceHierarchy[x]);
}
}
channel = channel.returnChannel(namespaceHierarchy[x]);
}
}
return channel;
},
// Pass in a channel namespace, function to be called, options, and context
// to call the function in to Subscribe. It will create a channel if one
// does not exist. Options can include a predicate to determine if it
// should be called (based on the data published to it) and a priority
// index.
subscribe: function(channelName, fn, options, context){
var channel = this.getChannel(channelName || "", false);
options = options || {};
context = context || {};
return channel.addSubscriber(fn, options, context);
},
// Pass in a channel namespace, function to be called, options, and context
// to call the function in to Subscribe. It will create a channel if one
// does not exist. Options can include a predicate to determine if it
// should be called (based on the data published to it) and a priority
// index.
once: function(channelName, fn, options, context){
options = options || {};
options.calls = 1;
return this.subscribe(channelName, fn, options, context);
},
// Returns a subscriber for a given subscriber id / named function and
// channel namespace
getSubscriber: function(identifier, channelName){
var channel = this.getChannel(channelName || "", true);
// We have to check if channel within the hierarchy exists and if it is
// an exact match for the requested channel
if (channel.namespace !== channelName) {
return null;
}
return channel.getSubscriber(identifier);
},
// Remove a subscriber from a given channel namespace recursively based on
// a passed-in subscriber id or named function.
remove: function(channelName, identifier){
var channel = this.getChannel(channelName || "", true);
if (channel.namespace !== channelName) {
return false;
}
channel.removeSubscriber(identifier);
},
// Publishes arbitrary data to a given channel namespace. Channels are
// called recursively downwards; a post to application:chat will post to
// application:chat:receive and application:chat:derp:test:beta:bananas.
// Called using Mediator.publish("application:chat", [ args ]);
publish: function(channelName){
var channel = this.getChannel(channelName || "", true);
if (channel.namespace !== channelName) {
return null;
}
var args = Array.prototype.slice.call(arguments, 1);
args.push(channel);
channel.publish(args);
}
};
// Alias some common names for easy interop
Mediator.prototype.on = Mediator.prototype.subscribe;
Mediator.prototype.bind = Mediator.prototype.subscribe;
Mediator.prototype.emit = Mediator.prototype.publish;
Mediator.prototype.trigger = Mediator.prototype.publish;
Mediator.prototype.off = Mediator.prototype.remove;
// Finally, expose it all.
Mediator.Channel = Channel;
Mediator.Subscriber = Subscriber;
Mediator.version = "0.9.8";
return Mediator;
}));
/* Mediator.js EOF */
}
})();