-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.js
2194 lines (1813 loc) · 74.8 KB
/
event.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Alternate event API augmentation class.
*
* @module eventx-core
*/
// TODO:
// - Add support for internal/locked subscriptions (can detach internally only)
var isObject = Y.Lang.isObject,
isArray = Y.Lang.isArray,
proto = Y.Object,
toArray = Y.Array,
arrayIndex = toArray.indexOf, // Y.Array.indexOf
ArrayProto = Array.prototype,
push = ArrayProto.push,
slice = ArrayProto.slice,
STRING = 'string',
FUNCTION = 'function',
ON = 'on',
AFTER = 'after',
DEFAULT = '@default',
SUBSCRIBE = '@subscribe',
UNSUBSCRIBE = '@unsubscribe',
FIRE = '@fire',
NOOP = function () {},
ABORT = {}; // Used for fireOnce events that were stopped
/**
Class to encapsulate an event subscription. Stores the callback, execution
context (`this` in the callback), and any bound arguments to pass to the
callback after the event object.
_args_ is expected to be an array containing:
1. The event type (string)
1. The subscription callback (function)
1. Optionally the `this` object override for the callback. Defaults to _target_.
1. Optionally any additional arguments to pass to the callback
Alternately, can be used to encapsulate a set of Subscriptions by passing an
array of Subscription objects as _type_.
@class Subscription
@param {EventTarget|Subscription[]} target From whence the
subscription was made or an array of subscriptions
@param {Array} args See above
@param {String} phase The subscription phase
@param {Any} details Data returned from the event's `parseSignature()`
method if it has one defined
**/
function Subscription(target, args, details) {
// Ew, but convenient to have new Subscription handle both single and multi
if (!args) {
return new BatchSubscription(target);
}
this.target = target;
this.details = details;
this.type = args[0];
this.callback = args[1];
// Support contextFn in the form of thisObj passed as a function
var thisObj = args[2];
if (typeof thisObj === FUNCTION) {
this.contextFn = thisObj;
} else {
this.thisObj = thisObj;
}
// Support late binding of callback function
this.lateBound = (typeof this.callback === STRING);
if (args.length > 3) {
this.payload = slice.call(args, 3);
}
}
Subscription.prototype = {
/**
Call the subscribed callback with the provided arguments, followed by
any bound subscription arguments.
@method notify
@param {Any[]} [args] Array of arguments to send to callbacks. For
emitFacade events, there will be only one arg: the
EventFacade object.
**/
notify: function (args) {
var thisObj = this.thisObj,
callback = this.callback,
ret;
if (this.payload) {
if (args) {
args = toArray(args, 0, true);
push.apply(args, this.payload);
} else {
args = this.payload;
}
}
if (!thisObj) {
// TODO: Smart to allow contextFn to decide thisObj based on
// additional subscription args? Foot gun?
thisObj = (this.contextFn && this.contextFn.apply(this, args)) ||
this.target;
}
ret = (this.lateBound ? thisObj[callback] : callback)
.apply(thisObj, args);
// Unfortunate cost of back compat. Would rather deprecate once and
// onceAfter in favor of e.detach(), but that would still leave
// non-emitting events to have to detach( args or sub ). Still,
// I think that's fine to require that!
if (this.details.once) {
this.detach();
}
return ret;
},
/**
Detaches the subscription from the subscribed target. Convenience for
`this.target.detach(this);`.
@method detach
**/
detach: function () {
this.target.detach(this);
}
};
/**
Wraps an array of Subscriptions. Returned from new Y.Subscription(arrayOfSubs).
@class BatchSubscription
@constructor
@param {Subscription[]} {subs} The array of Subscriptions
**/
function BatchSubscription(subs) {
this.subs = subs;
}
Y.extend(BatchSubscription, Subscription, {
// batch subscriptions aren't for notification
notify: NOOP,
/**
Calls `detach()` on each sub in the batch.
@method detach
**/
detach: function () {
var subs = this.subs,
i, len;
for (i = 0, len = subs.length; i < len; ++i) {
sub = this.subs[i];
if (sub && sub.detach) {
sub.detach();
}
}
}
});
/**
Event object passed as the first parameter to event subscription callbacks.
Data to distinguish each instance is supplied in the _payload_ array. If the
first argument is an object (recommended), it is used to seed the event's `data`
property, which is what houses the data for the `get()` and `set()` methods.
All payload data in the passed array form is stored as the `details` property
of the event's `data` collection. While it is recommended to use `get()` to
access event data values, you can access the raw data at `e.data.details`.
@class EventFacade
@param {String} type The name of the event
@param {EventTarget} target EventTarget from which `fire()` was called
@param {Any[]} [payload] Data specific to this event, passed
**/
function EventFacade(type, target, payload) {
var data;
this.type = type;
if (payload) {
this.details = payload;
payload = payload[0];
if (isObject(payload, true)) {
data = (payload instanceof EventFacade) ? payload.data : payload;
}
}
this.data = data || {};
this.data.target = target;
}
EventFacade.prototype = {
/**
Collection of getters to apply special logic to accessing certain data
properties. This is a shared object on the prototype, so be careful if you
modify it.
@property _getter
@type {Object}
@protected
**/
_getter: {
details: function () { return this.details; }
},
/**
Collection of setters to apply special logic to assigning certain data
properties. This is a shared object on the prototype, so be careful if you
modify it.
@property _setter
@type {Object}
@protected
**/
_setter: {},
/**
Has `e.preventDefault()` been called on this event?
@property prevented
@type {Boolean}
@default `false`
**/
prevented: false,
/**
Has `e.stopPropagation()` or `e.stopImmediatePropagation()` been called on
this event?
Value will be one of:
* 0 - unstopped (default)
* 1 - `e.stopPropagation()` called
* 2 - `e.stopImmediatePropagation()` called
@property prevented
@type {Number}
@default `0`
**/
stopped : 0,
/**
Disables any default behavior (`defaultFn`) associated with the event. This
will also prevent any `after()` subscribers from being executed.
@method preventDefault
@chainable
**/
preventDefault: function () {
this.prevented = true;
return this;
},
/**
Stops the event from bubbling to subsequent bubble targets. All subscribers
on the current bubble target will be executed.
Does not prevent the event's default behavior or its `after()` subscribers
from being called.
@method stopPropagation
@chainable
**/
stopPropagation: function () {
// It might have been stopped with 2 already
if (!this.stopped) {
this.stopped = 1;
}
return this;
},
/**
Stops the event from bubbling to subsequent bubble targets and stops
notification of additional subscribers on the current bubble target.
Does not prevent the event's default behavior or its `after()` subscribers
from being called.
@method stopImmediatePropagation
@chainable
**/
stopImmediatePropagation: function () {
this.stopped = 2;
return this;
},
/**
Convenience function to do both `e.preventDefault()` and
`e.stopPropagation()`. Pass a truthy value as _immediate_ to
`e.stopImmediatePropagation()` instead.
@method halt
@param {Boolean} [immediate] Trigger `e.stopImmediatePropagation()`
@chainable
**/
halt: function (immediate) {
this.prevented = true;
this.stopped = immediate ? 2 : 1;
return this;
},
/**
Detaches the subscription for this callback.
@method detach
@chainable
**/
detach: function () {
if (this.subscription && this.subscription.detach) {
this.subscription.detach();
}
return this;
},
/**
Get a property from the event's data collection supplied at event creation.
If a getter is defined for the property, its return value will be returned.
Otherwise, the property from the data collection, if present, will be
returned.
@method get
@param {String} name Data property name
@param {Boolean} noProp If no getter is defined, return only the value from
the `data` collection. Do not fall back to
retrieving property on the instance.
@return {Any} whatever is stored in the data property
**/
get: function (name, noProp) {
if (this._getter[name]) {
return this._getter[name].call(this, name);
} else {
return (noProp || name in this.data) ? this.data[name] : this[name];
}
},
/**
Set a property in the event's data collection. If a setter is defined for
the property, it will be called with the _name_ and _val_. Otherwise, the
property and value will be assigned to the data collection directly.
@method set
@param {String} name Data property name
@param {Any} val The value to assign
@chainable
**/
set: function (name, val) {
if (this._setter[name]) {
this._setter[name].call(this, name, val);
} else {
this.data[name] = val;
}
return this;
}
};
if (Object.defineProperties) {
Object.defineProperties(EventFacade.prototype, {
target: {
get: function () { return this.get('target', true); },
set: function (val) { this.set('target', val); }
},
currentTarget: {
get: function () { return this.get('currentTarget', true); },
set: function (val) { this.set('currentTarget', val); }
}
});
}
/**
Collection of behaviors for subscribing to and firing a named custom event.
This class is meant to be a scaffolding for customizations. The default
method implementations support the following customizations:
* config.defaultFn(e) - Behavior executed after `on()` subscribers, before
`after()` subscribers, and only if `e.preventDefault()` isn't called.
* config.preventable (boolean) - If `e.preventDefault()` does anything.
* config.preventedFn(e) - Called if `e.preventDefault()` is called.
* config.stoppedFn(e) - Called if `e.stopPropagation()` is called.
* config.bubbles (boolean) - Allow or disallow bubbling for this event. Default
is `true`.
* config.allowDups (boolean) - Allow or disallow duplicate subscriptions.
Default is `true`.
* config.on(target, subscription, details) - Execute this code when
subscriptions are made to the event. Return truthy value to abort the
subscription. Return a different Subscription to avoid registering the one
passed in.
* config.detach(target, subscription) - Likewise when subscriptions are removed
* config.parseSignature(target, subArgs, details) - Support custom subscription
signatures. Add additional data to the _details_ object to store in the
subscription object's `details` property.
* config.publish(target) - Execute this code when the event is published.
* config.Event(type, target, payload) - Class used to create the event objects
that are passed to subscribers.
* config.Subscription(target, args, details) - Class used to encapsulate a
subscription to the event.
Additional properties and methods can be added to the event for reference from
any of the configured methods, or from overrides to the methods defined on the
CustomEvent prototype. All properties of the _config_ object are mixed onto
the event.
The primary use case for custom event creation is through static definition
on a class in the `EventTarget.configure()` call. More events can be added to
a class or specifically to a class instance using either the class's static or
instance `publish()` method.
```
Y.EventTarget.configure(MyClass, { map of events to configs }, defaultEvent);
MyClass.publish('eventX', { bubbles: false });
instance.publish('eventY', { preventable: false });
```
Events published on a class or instance derive their behavior from a default
event defined during `configure()`. The default event is a custom event whose
configured behaviors are used when `on()` or `fire()` are called for events
that aren't explicitly published for the class or instance. To create an event
that derives from a different set of event behaviors, pass the desired
prototype event as _inheritsFrom_.
@class CustomEvent
@param {Object} [config] overrides and additional properties for the event
@param {CustomEvent} [inheritsFrom=CustomEvent.prototype] prototype for this
event
**/
function CustomEvent(config, inheritsFrom) {
var instance, key;
if (!inheritsFrom && !(this instanceof CustomEvent)) {
inheritsFrom = CustomEvent.prototype;
}
instance = inheritsFrom ? proto(inheritsFrom) : this;
// Override instance properties and methods from input config
if (config) {
for (key in config) {
if (config.hasOwnProperty(key)) {
instance[key] = config[key];
}
}
}
// Might return instance of another prototype
return instance;
}
CustomEvent.prototype = {
/**
The class constructor for subscriptions to this event. Unless the
`subscribe` method has been overwritten with code that calls
this constructor a different way, it will receive the following arguments:
* `target` - the EventTarget that called `on()` or `after()`
* `args` - the subscription arguments (type, callback, thisObj, args)
* `details` - metadata about the subscription, such as phase, whether it's
a `delegate()` or `once()` subscription, as well as any
additional properties added by `parseSignature` if the event
is configured with such a method.
@property Subscription
@type {Function}
**/
Subscription: Subscription,
/**
Coordinates the various steps involved in subscribing to this event.
Typically defined events will not need to override this method. The
arguments array received as the third parameter is passed to the
`parseSignature` method for any adjustments needed. The methods
called from here include:
* `parseSignature(target, args, subDetails)` if defined for this event
* `new this.Subscription(target, args, subDetails)` passing the
processed argument array and subscription metadata, augmented with any
data from `parseSignature`
* `isSubscribed(target, sub)` if `preventDups` is truthy
* `on(target, sub)` if `on` is defined for this event
The default signature of `args` for direct subscriptions is:
* type (string)
* callback (function)
* thisObj (optional `this` override for callback)
* ...argN (optional additional bound subscription args to pass to callback)
The default signature of `args` for delegate subscriptions is:
* type (string)
* callback (function)
* filter (function)
* thisObj (optional `this` override for callback)
* ...argN (optional additional bound subscription args to pass to callback)
The _details_ object contains instructions and/or information for how to
create or customize the subscription. The default properties looked for are:
* phase (string) - which phase to register the subscription in
* delegate (boolean) - do _args_ reflect a delegate signature
* once (boolean) - should the subscription auto-detach after notification
@method subscribe
@param {EventTarget} target The instance to own the subscription
@param {Array} args Arguments listed above
@param {Object} details The subscription metadata (e.g. phase, etc)
@return {Subscription}
**/
subscribe: function (target, args, details) {
if (this.parseSignature) {
this.parseSignature(target, args, details);
}
var yuievt = target._yuievt,
fired = this.fireOnce && yuievt.fired && yuievt.fired[args[0]],
sub = (fired !== ABORT) &&
new this.Subscription(target, args, details),
abort = sub && this.preventDups && this.isSubscribed(target, sub);
if (!abort) {
if (this.on) {
abort = this.on(target, sub);
}
// Register the subscription
if (!abort && !fired) {
this.registerSub(target, sub);
} else if (abort.detach) {
// Allow on() to return an alternate Subscription.
// It is assumed that this subscription was registered on the
// appropriate target.
sub = abort;
abort = false;
}
if (this.fireOnce && fired) {
sub.notify(fired);
abort = true;
}
}
return abort ? null : sub;
},
/**
Add a Subscription to the target's subs collection.
@method registerSub
@param {EventTarget} target The host of the event subscription
@param {Subscription} sub The subscription to store
**/
registerSub: function (target, sub) {
var subs = target._yuievt.subs;
// target._yuievt.subs.foo
subs = subs[sub.type] || (subs[sub.type] = {});
// target._yuievt.subs.foo.before
subs = subs[sub.details.phase] || (subs[sub.details.phase] = []);
// target._yuievt.subs.foo.before.push(sub)
subs.push(sub);
},
/**
Checks to see if a duplicate subscription exists.
@method isSubscribed
@param target {Object}
@param sub {Subscription} an instance of this.Subscription
@return {Boolean} true (or a truthy value) to abort the subscription
**/
isSubscribed: function (target, sub) {
if (target._yuievt) {
if (sub.details && sub.details.originalSub) {
sub = sub.details.originalSub;
}
var type = sub.type,
subs = target._yuievt.subs[type],
details = sub.details,
phase = details.phase,
callback = sub.callback,
cmp, i;
if (subs && subs[phase]) {
subs = subs[phase];
for (i = subs.length - 1; i >= 0; --i) {
cmp = subs[i];
if (cmp.details && cmp.details.originalSub) {
cmp = cmp.details.originalSub;
}
if (type === cmp.type
&& phase === cmp.details.phase
&& callback === cmp.callback) {
return true;
}
}
}
}
return false;
},
/**
Control whether duplicate subscriptions to this event should be allowed.
If true, the `isSubscribed` method will be called to search
the existing subscriptions for duplicates. If one is found, the
subscription will be aborted.
@property preventDups
@type {Boolean}
@default `undefined` (falsey)
**/
/**
Notifies subscribers for the event.
@method fire
@param {EventTarget} target The instance from which fire was called
@param {String} type The event type to dispatch
@param args* {any} additional args passed `fire(type, _here_...)`
**/
fire: function (target, type) {
var yuievt = target._yuievt,
path = (this.bubbles && yuievt.bubblePath) ?
this.resolveBubblePath(target) : [target],
fireOnce = this.fireOnce,
fired = fireOnce && yuievt.fired && yuievt.fired[type],
payload, ret;
// Only proceed if there are subscribers or it's a fireOnce event that
// hasn't been fired
if (this.hasSubs(path, type) || (fireOnce && !fired)) {
if (arguments.length > 2) {
payload = toArray(arguments, 2, true);
}
ret = this.notify(path, type, payload, ON);
if (ret !== false) {
this.notify(path, type, payload, AFTER);
}
}
if (fireOnce && !fired) {
// Clear subscribers
yuievt.subs[type] = null;
if (!yuievt.fired) {
yuievt.fired = {};
}
yuievt.fired[type] = (ret === false) ? ABORT : (payload || []);
}
},
/**
Checks for subscribers along the bubble path if necessary.
@method hasSubs
@param {EventTarget} path The bubble path
@param {String} type The event type to collect subscriptions for
@return {Boolean}
**/
hasSubs: function (path, type) {
for (var i = 0, len = path.length; i < len; ++i) {
if (path[i]._yuievt.subs[type]) {
return true;
}
}
return false;
},
/**
Flattens the bubble path for a given root instance. Flattens using a
breadth-first algorithm, so given the following bubble structure:
```
. (D) (E) (D) (F)
. \ | | /
. (B) (C) bubble up to
. \ /
. (A) bubbles up to
```
The resulting bubble path would be [A, B, C, D, E, F], and not
[A, B, D, E, C, F] (depth-first). Also note duplicate targets are
ignored. The first appearance in the bubble path wins.
@method resolveBubblePath
@param root {Object} the origin of the event to bubble (A in the diagram)
@return {Array} the ordered list of target instances
**/
resolveBubblePath: function (root) {
var targets = [root],
known = {},
path = [],
target, yuid, i;
// Add to the end of the targets array as we iterate. This creates a
// bubble path where A's immediate bubble targets are all notified, then
// each of their respective bubble targets are notified and so on.
// (breadth first)
for (i = 0; i < targets.length; ++i) {
target = targets[i];
yuid = target._yuievt && Y.stamp(target);
// protect against infinite loops
if (yuid && !known[yuid]) {
known[yuid] = true;
path.push(target);
if (target._yuievt.bubblePath) {
// Push this target's bubble targets to the end of the
// targets array we're looping over.
push.apply(targets, target._yuievt.bubblePath);
}
}
}
return path;
},
/**
This event can be subscribed to from other objects in a bubble path, added
to with `target.addTarget(parentTarget)`
@property bubbles
@type {Boolean}
@default `true`
**/
bubbles: true,
/**
Executes all the subscribers in a bubble path for an event in a given
phase ("on" or "after"). Used by `fire()`.
If a subscriber calls `e.stopImmediatePropagation()`, no
further subscribers will be executed, and if a subscriber calls
`e.stopPropagation()`, no further bubble targets will be
notified.
@method notify
@param {EventTarget[]} path Bubble targets to be notified
@param {String} type The name of the event
@param {Any[]} payload The arguments to pass to the subscription callback
@param {String} phase The phase of subscribers on the targets to notify
@return {Boolean} `false` if a subscriber halted the event
**/
notify: function (path, type, payload, phase) {
var i, len, subs, j, jlen, ret;
for (i = 0, len = path.length; i < len && ret !== false; ++i) {
subs = path[i]._yuievt.subs[type];
subs = subs && subs[phase];
if (subs) {
// Snapshot subscriber list to avoid array changing during
// notifications (e.g. once() detaches)
subs = subs.slice();
for (j = 0, jlen = subs.length; j < jlen; ++j) {
ret = subs[j].notify(payload);
// Erg, I hate the return false support
if (ret === false) {
// Clip bubble path. Propagation has been stopped, and
// on() and after() are notification phases of the same
// event, not separate events.
path.splice(i + 1);
return false;
}
}
}
}
},
/**
Remove a subscription or set of subscriptions for this event. If the event
has a `detach()` method defined, it will be executed and can prevent the
subscription removal by returning a truthy value.
@method unsubscribe
@param {EventTarget} target The instance from which `detach()` was called
@param {Array} args Arguments passed to `detach(..)`
**/
unsubscribe: function (target, args) {
var sub = args[0],
allSubs = target._yuievt.subs,
remove, i, len, subs, phase, abort;
// Use case: detach(type, ...);
if (typeof sub === STRING) {
subs = allSubs[sub];
phase = args[2];
if (!subs || (phase && !subs[phase])) {
return;
}
remove = [];
callback = args[1];
if (phase) {
push.apply(remove, subs[phase]);
} else {
for (phase in subs) {
if (subs.hasOwnProperty(phase)) {
push.apply(remove, subs[phase]);
}
}
}
// Not the most efficient algorithm, but avoids deep nesting. We'll
// call it an opportunity for performance improvement (at the
// expense of code size).
if (args[1]) {
callback = args[1];
subs = remove;
remove = [];
for (i = 0, len = subs.length; i < len; ++i) {
if (subs[i].callback === callback) {
remove.push(subs[i]);
}
}
}
// Avoids code bloat from having to test and call this.detach for
// each discovered sub.
sub = new BatchSubscription(remove);
}
if (sub instanceof BatchSubscription) {
return sub.detach();
}
// use case target.detach(sub)
// Note: this.detach not to be mistaken with sub.detach. this.detach
// is the configuration option for the CustomEvent to do something
// special during the detach phase of the subscription.
if (this.detach) {
abort = this.detach(sub);
}
if (!abort) {
this.unregisterSub(target, sub);
}
},
/**
Remove a Subscription from the target's subs collection. If there are no
remaining subscriptions in the phase or any phase of the sub's type, the
empty objects are pruned from the target's subs collection.
@method registerSub
@param {EventTarget} target The host of the event subscription
@param {Subscription} sub The subscription to remove
**/
unregisterSub: function (target, sub) {
var allSubs = target._yuievt.subs,
type = sub.type,
phase = sub.details.phase,
subs = allSubs[type] && allSubs[type][phase],
i;
// remove the callback in case the event is currently firing,
// since the subscriber list is copied before notifications
// begin.
sub.callback = NOOP;
if (subs) {
// Step 1. remove it from the target's _yuievt.subs collection
for (i = subs.length - 1; i >= 0; --i) {
if (subs[i] === sub) {
subs.splice(i, 1);
break;
}
}
// Step 2. prune empty objects in _yuievt.subs
if (!subs.length) {
subs = allSubs[type];
subs[phase] = null;
cleanup = true;
for (phase in subs) {
if (subs.hasOwnProperty(phase) && subs[phase]) {
// Still has subs in another phase
cleanup = false;
break;
}
}
if (cleanup) {
allSubs[type] = null;
// TODO: try to reset _yuievt.subs to {} if this was the
// last subscription to any event?
}
}
}
}
};
/**
Class to encapsulate custom event subscriptions. This is also assigned to the
`CustomEvent.prototype` for individual event overrides, but provided statically
for subclassing.
@property Subscription
@type {Function}
@static
**/
CustomEvent.Subscription = Subscription;
/**
Custom event used by `publish` and `configure` as the inherited event when an
event is configured with `emitFacade: true`. Can be used as a default event
or passed as the _inheritsFrom_ param to `publish` directly.
Notifies subscribers with an EventFacade, and supports `defaultFn` and friends.
@property FacadeEvent
@type {CustomEvent}
@static
**/
CustomEvent.FacadeEvent = new CustomEvent({
emitFacade: true,
subscribe: function (target, args, details) {
if (!isArray(args)) {
args = toArray(args, 0, true);
}
if (this.parseSignature) {
this.parseSignature(target, args, details);
}
if (details.delegate) {
this.delegate(target, args, details);
}
var yuievt = target._yuievt,
fired = this.fireOnce && yuievt.fired && yuievt.fired[args[0]],
abort = fired &&
(fired === ABORT ||
(details.phase === AFTER && fired[0].prevented)),
sub = !abort && new this.Subscription(target, args, details);
if (sub && this.preventDups) {
abort = this.isSubscribed(target, sub);
}
if (!abort) {
// Custom behavior hook
if (this.on) {
abort = this.on(target, sub);
}
// Register the subscription
if (!abort && !fired) {
this.registerSub(target, sub);
} else if (abort.detach) {
// Allow on() to return an alternate Subscription.
// It is assumed that this subscription was registered on the
// appropriate target.
sub = abort;
abort = false;
}
if (this.fireOnce && fired) {
sub.notify(fired);
abort = true;
}
}
return abort ? null : sub;
},