Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
YUI.add('event-base', function (Y, NAME) {
2
 
3
/*
4
 * DOM event listener abstraction layer
5
 * @module event
6
 * @submodule event-base
7
 */
8
 
9
/**
10
 * The domready event fires at the moment the browser's DOM is
11
 * usable. In most cases, this is before images are fully
12
 * downloaded, allowing you to provide a more responsive user
13
 * interface.
14
 *
15
 * In YUI 3, domready subscribers will be notified immediately if
16
 * that moment has already passed when the subscription is created.
17
 *
18
 * One exception is if the yui.js file is dynamically injected into
19
 * the page.  If this is done, you must tell the YUI instance that
20
 * you did this in order for DOMReady (and window load events) to
21
 * fire normally.  That configuration option is 'injected' -- set
22
 * it to true if the yui.js script is not included inline.
23
 *
24
 * This method is part of the 'event-ready' module, which is a
25
 * submodule of 'event'.
26
 *
27
 * @event domready
28
 * @for YUI
29
 */
30
Y.publish('domready', {
31
    fireOnce: true,
32
    async: true
33
});
34
 
35
if (YUI.Env.DOMReady) {
36
    Y.fire('domready');
37
} else {
38
    Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready');
39
}
40
 
41
/**
42
 * Custom event engine, DOM event listener abstraction layer, synthetic DOM
43
 * events.
44
 * @module event
45
 * @submodule event-base
46
 */
47
 
48
/**
49
 * Wraps a DOM event, properties requiring browser abstraction are
50
 * fixed here.  Provids a security layer when required.
51
 * @class DOMEventFacade
52
 * @param ev {Event} the DOM event
53
 * @param currentTarget {HTMLElement} the element the listener was attached to
54
 * @param wrapper {CustomEvent} the custom event wrapper for this DOM event
55
 */
56
 
57
    var ua = Y.UA,
58
 
59
    EMPTY = {},
60
 
61
    /**
62
     * webkit key remapping required for Safari < 3.1
63
     * @property webkitKeymap
64
     * @private
65
     */
66
    webkitKeymap = {
67
        63232: 38, // up
68
        63233: 40, // down
69
        63234: 37, // left
70
        63235: 39, // right
71
        63276: 33, // page up
72
        63277: 34, // page down
73
        25:     9, // SHIFT-TAB (Safari provides a different key code in
74
                   // this case, even though the shiftKey modifier is set)
75
        63272: 46, // delete
76
        63273: 36, // home
77
        63275: 35  // end
78
    },
79
 
80
    /**
81
     * Returns a wrapped node.  Intended to be used on event targets,
82
     * so it will return the node's parent if the target is a text
83
     * node.
84
     *
85
     * If accessing a property of the node throws an error, this is
86
     * probably the anonymous div wrapper Gecko adds inside text
87
     * nodes.  This likely will only occur when attempting to access
88
     * the relatedTarget.  In this case, we now return null because
89
     * the anonymous div is completely useless and we do not know
90
     * what the related target was because we can't even get to
91
     * the element's parent node.
92
     *
93
     * @method resolve
94
     * @private
95
     */
96
    resolve = function(n) {
97
        if (!n) {
98
            return n;
99
        }
100
        try {
101
            if (n && 3 == n.nodeType) {
102
                n = n.parentNode;
103
            }
104
        } catch(e) {
105
            return null;
106
        }
107
 
108
        return Y.one(n);
109
    },
110
 
111
    DOMEventFacade = function(ev, currentTarget, wrapper) {
112
        this._event = ev;
113
        this._currentTarget = currentTarget;
114
        this._wrapper = wrapper || EMPTY;
115
 
116
        // if not lazy init
117
        this.init();
118
    };
119
 
120
Y.extend(DOMEventFacade, Object, {
121
 
122
    init: function() {
123
 
124
        var e = this._event,
125
            overrides = this._wrapper.overrides,
126
            x = e.pageX,
127
            y = e.pageY,
128
            c,
129
            currentTarget = this._currentTarget;
130
 
131
        this.altKey   = e.altKey;
132
        this.ctrlKey  = e.ctrlKey;
133
        this.metaKey  = e.metaKey;
134
        this.shiftKey = e.shiftKey;
135
        this.type     = (overrides && overrides.type) || e.type;
136
        this.clientX  = e.clientX;
137
        this.clientY  = e.clientY;
138
 
139
        this.pageX = x;
140
        this.pageY = y;
141
 
142
        // charCode is unknown in keyup, keydown. keyCode is unknown in keypress.
143
        // FF 3.6 - 8+? pass 0 for keyCode in keypress events.
144
        // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup.
145
        // Webkit and IE9+? duplicate charCode in keyCode.
146
        // Opera never sets charCode, always keyCode (though with the charCode).
147
        // IE6-8 don't set charCode or which.
148
        // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and
149
        // which=charCode in keypress.
150
        //
151
        // Moral of the story: (e.which || e.keyCode) will always return the
152
        // known code for that key event phase. e.keyCode is often different in
153
        // keypress from keydown and keyup.
154
        c = e.keyCode || e.charCode;
155
 
156
        if (ua.webkit && (c in webkitKeymap)) {
157
            c = webkitKeymap[c];
158
        }
159
 
160
        this.keyCode = c;
161
        this.charCode = c;
162
        // Fill in e.which for IE - implementers should always use this over
163
        // e.keyCode or e.charCode.
164
        this.which = e.which || e.charCode || c;
165
        // this.button = e.button;
166
        this.button = this.which;
167
 
168
        this.target = resolve(e.target);
169
        this.currentTarget = resolve(currentTarget);
170
        this.relatedTarget = resolve(e.relatedTarget);
171
 
172
        if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
173
            this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
174
        }
175
 
176
        if (this._touch) {
177
            this._touch(e, currentTarget, this._wrapper);
178
        }
179
    },
180
 
181
    stopPropagation: function() {
182
        this._event.stopPropagation();
183
        this._wrapper.stopped = 1;
184
        this.stopped = 1;
185
    },
186
 
187
    stopImmediatePropagation: function() {
188
        var e = this._event;
189
        if (e.stopImmediatePropagation) {
190
            e.stopImmediatePropagation();
191
        } else {
192
            this.stopPropagation();
193
        }
194
        this._wrapper.stopped = 2;
195
        this.stopped = 2;
196
    },
197
 
198
    preventDefault: function(returnValue) {
199
        var e = this._event;
200
        e.preventDefault();
201
        if (returnValue) {
202
            e.returnValue = returnValue;
203
        }
204
        this._wrapper.prevented = 1;
205
        this.prevented = 1;
206
    },
207
 
208
    halt: function(immediate) {
209
        if (immediate) {
210
            this.stopImmediatePropagation();
211
        } else {
212
            this.stopPropagation();
213
        }
214
 
215
        this.preventDefault();
216
    }
217
 
218
});
219
 
220
DOMEventFacade.resolve = resolve;
221
Y.DOM2EventFacade = DOMEventFacade;
222
Y.DOMEventFacade = DOMEventFacade;
223
 
224
    /**
225
     * The native event
226
     * @property _event
227
     * @type {DOMEvent}
228
     * @private
229
     */
230
 
231
    /**
232
    The name of the event (e.g. "click")
233
 
234
    @property type
235
    @type {String}
236
    **/
237
 
238
    /**
239
    `true` if the "alt" or "option" key is pressed.
240
 
241
    @property altKey
242
    @type {Boolean}
243
    **/
244
 
245
    /**
246
    `true` if the shift key is pressed.
247
 
248
    @property shiftKey
249
    @type {Boolean}
250
    **/
251
 
252
    /**
253
    `true` if the "Windows" key on a Windows keyboard, "command" key on an
254
    Apple keyboard, or "meta" key on other keyboards is pressed.
255
 
256
    @property metaKey
257
    @type {Boolean}
258
    **/
259
 
260
    /**
261
    `true` if the "Ctrl" or "control" key is pressed.
262
 
263
    @property ctrlKey
264
    @type {Boolean}
265
    **/
266
 
267
    /**
268
     * The X location of the event on the page (including scroll)
269
     * @property pageX
270
     * @type {Number}
271
     */
272
 
273
    /**
274
     * The Y location of the event on the page (including scroll)
275
     * @property pageY
276
     * @type {Number}
277
     */
278
 
279
    /**
280
     * The X location of the event in the viewport
281
     * @property clientX
282
     * @type {Number}
283
     */
284
 
285
    /**
286
     * The Y location of the event in the viewport
287
     * @property clientY
288
     * @type {Number}
289
     */
290
 
291
    /**
292
     * The keyCode for key events.  Uses charCode if keyCode is not available
293
     * @property keyCode
294
     * @type {Number}
295
     */
296
 
297
    /**
298
     * The charCode for key events.  Same as keyCode
299
     * @property charCode
300
     * @type {Number}
301
     */
302
 
303
    /**
304
     * The button that was pushed. 1 for left click, 2 for middle click, 3 for
305
     * right click.  This is only reliably populated on `mouseup` events.
306
     * @property button
307
     * @type {Number}
308
     */
309
 
310
    /**
311
     * The button that was pushed.  Same as button.
312
     * @property which
313
     * @type {Number}
314
     */
315
 
316
    /**
317
     * Node reference for the targeted element
318
     * @property target
319
     * @type {Node}
320
     */
321
 
322
    /**
323
     * Node reference for the element that the listener was attached to.
324
     * @property currentTarget
325
     * @type {Node}
326
     */
327
 
328
    /**
329
     * Node reference to the relatedTarget
330
     * @property relatedTarget
331
     * @type {Node}
332
     */
333
 
334
    /**
335
     * Number representing the direction and velocity of the movement of the mousewheel.
336
     * Negative is down, the higher the number, the faster.  Applies to the mousewheel event.
337
     * @property wheelDelta
338
     * @type {Number}
339
     */
340
 
341
    /**
342
     * Stops the propagation to the next bubble target
343
     * @method stopPropagation
344
     */
345
 
346
    /**
347
     * Stops the propagation to the next bubble target and
348
     * prevents any additional listeners from being exectued
349
     * on the current target.
350
     * @method stopImmediatePropagation
351
     */
352
 
353
    /**
354
     * Prevents the event's default behavior
355
     * @method preventDefault
356
     * @param returnValue {string} sets the returnValue of the event to this value
357
     * (rather than the default false value).  This can be used to add a customized
358
     * confirmation query to the beforeunload event).
359
     */
360
 
361
    /**
362
     * Stops the event propagation and prevents the default
363
     * event behavior.
364
     * @method halt
365
     * @param immediate {boolean} if true additional listeners
366
     * on the current target will not be executed
367
     */
368
(function() {
369
 
370
/**
371
 * The event utility provides functions to add and remove event listeners,
372
 * event cleansing.  It also tries to automatically remove listeners it
373
 * registers during the unload event.
374
 * @module event
375
 * @main event
376
 * @submodule event-base
377
 */
378
 
379
/**
380
 * The event utility provides functions to add and remove event listeners,
381
 * event cleansing.  It also tries to automatically remove listeners it
382
 * registers during the unload event.
383
 *
384
 * @class Event
385
 * @static
386
 */
387
 
388
Y.Env.evt.dom_wrappers = {};
389
Y.Env.evt.dom_map = {};
390
 
391
var _eventenv = Y.Env.evt,
392
    config = Y.config,
393
    win = config.win,
394
    add = YUI.Env.add,
395
    remove = YUI.Env.remove,
396
 
397
    onLoad = function() {
398
        YUI.Env.windowLoaded = true;
399
        Y.Event._load();
400
        remove(win, "load", onLoad);
401
    },
402
 
403
    onUnload = function() {
404
        Y.Event._unload();
405
    },
406
 
407
    EVENT_READY = 'domready',
408
 
409
    COMPAT_ARG = '~yui|2|compat~',
410
 
411
    shouldIterate = function(o) {
412
        try {
413
            // TODO: See if there's a more performant way to return true early on this, for the common case
414
            return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !Y.DOM.isWindow(o));
415
        } catch(ex) {
416
            return false;
417
        }
418
    },
419
 
420
    // aliases to support DOM event subscription clean up when the last
421
    // subscriber is detached. deleteAndClean overrides the DOM event's wrapper
422
    // CustomEvent _delete method.
423
    _ceProtoDelete = Y.CustomEvent.prototype._delete,
424
    _deleteAndClean = function(s) {
425
        var ret = _ceProtoDelete.apply(this, arguments);
426
 
427
        if (!this.hasSubs()) {
428
            Y.Event._clean(this);
429
        }
430
 
431
        return ret;
432
    },
433
 
434
Event = function() {
435
 
436
    /**
437
     * True after the onload event has fired
438
     * @property _loadComplete
439
     * @type boolean
440
     * @static
441
     * @private
442
     */
443
    var _loadComplete =  false,
444
 
445
    /**
446
     * The number of times to poll after window.onload.  This number is
447
     * increased if additional late-bound handlers are requested after
448
     * the page load.
449
     * @property _retryCount
450
     * @static
451
     * @private
452
     */
453
    _retryCount = 0,
454
 
455
    /**
456
     * onAvailable listeners
457
     * @property _avail
458
     * @static
459
     * @private
460
     */
461
    _avail = [],
462
 
463
    /**
464
     * Custom event wrappers for DOM events.  Key is
465
     * 'event:' + Element uid stamp + event type
466
     * @property _wrappers
467
     * @type CustomEvent
468
     * @static
469
     * @private
470
     */
471
    _wrappers = _eventenv.dom_wrappers,
472
 
473
    _windowLoadKey = null,
474
 
475
    /**
476
     * Custom event wrapper map DOM events.  Key is
477
     * Element uid stamp.  Each item is a hash of custom event
478
     * wrappers as provided in the _wrappers collection.  This
479
     * provides the infrastructure for getListeners.
480
     * @property _el_events
481
     * @static
482
     * @private
483
     */
484
    _el_events = _eventenv.dom_map;
485
 
486
    return {
487
 
488
        /**
489
         * The number of times we should look for elements that are not
490
         * in the DOM at the time the event is requested after the document
491
         * has been loaded.  The default is 1000@amp;40 ms, so it will poll
492
         * for 40 seconds or until all outstanding handlers are bound
493
         * (whichever comes first).
494
         * @property POLL_RETRYS
495
         * @type int
496
         * @static
497
         * @final
498
         */
499
        POLL_RETRYS: 1000,
500
 
501
        /**
502
         * The poll interval in milliseconds
503
         * @property POLL_INTERVAL
504
         * @type int
505
         * @static
506
         * @final
507
         */
508
        POLL_INTERVAL: 40,
509
 
510
        /**
511
         * addListener/removeListener can throw errors in unexpected scenarios.
512
         * These errors are suppressed, the method returns false, and this property
513
         * is set
514
         * @property lastError
515
         * @static
516
         * @type Error
517
         */
518
        lastError: null,
519
 
520
 
521
        /**
522
         * poll handle
523
         * @property _interval
524
         * @static
525
         * @private
526
         */
527
        _interval: null,
528
 
529
        /**
530
         * document readystate poll handle
531
         * @property _dri
532
         * @static
533
         * @private
534
         */
535
         _dri: null,
536
 
537
        /**
538
         * True when the document is initially usable
539
         * @property DOMReady
540
         * @type boolean
541
         * @static
542
         */
543
        DOMReady: false,
544
 
545
        /**
546
         * @method startInterval
547
         * @static
548
         * @private
549
         */
550
        startInterval: function() {
551
            if (!Event._interval) {
552
Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL);
553
            }
554
        },
555
 
556
        /**
557
         * Executes the supplied callback when the item with the supplied
558
         * id is found.  This is meant to be used to execute behavior as
559
         * soon as possible as the page loads.  If you use this after the
560
         * initial page load it will poll for a fixed time for the element.
561
         * The number of times it will poll and the frequency are
562
         * configurable.  By default it will poll for 10 seconds.
563
         *
564
         * <p>The callback is executed with a single parameter:
565
         * the custom object parameter, if provided.</p>
566
         *
567
         * @method onAvailable
568
         *
569
         * @param {string||string[]}   id the id of the element, or an array
570
         * of ids to look for.
571
         * @param {function} fn what to execute when the element is found.
572
         * @param {object}   p_obj an optional object to be passed back as
573
         *                   a parameter to fn.
574
         * @param {boolean|object}  p_override If set to true, fn will execute
575
         *                   in the context of p_obj, if set to an object it
576
         *                   will execute in the context of that object
577
         * @param checkContent {boolean} check child node readiness (onContentReady)
578
         * @static
579
         * @deprecated Use Y.on("available")
580
         */
581
        // @TODO fix arguments
582
        onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
583
 
584
            var a = Y.Array(id), i, availHandle;
585
 
586
            for (i=0; i<a.length; i=i+1) {
587
                _avail.push({
588
                    id:         a[i],
589
                    fn:         fn,
590
                    obj:        p_obj,
591
                    override:   p_override,
592
                    checkReady: checkContent,
593
                    compat:     compat
594
                });
595
            }
596
            _retryCount = this.POLL_RETRYS;
597
 
598
            // We want the first test to be immediate, but async
599
            setTimeout(Event._poll, 0);
600
 
601
            availHandle = new Y.EventHandle({
602
 
603
                _delete: function() {
604
                    // set by the event system for lazy DOM listeners
605
                    if (availHandle.handle) {
606
                        availHandle.handle.detach();
607
                        return;
608
                    }
609
 
610
                    var i, j;
611
 
612
                    // otherwise try to remove the onAvailable listener(s)
613
                    for (i = 0; i < a.length; i++) {
614
                        for (j = 0; j < _avail.length; j++) {
615
                            if (a[i] === _avail[j].id) {
616
                                _avail.splice(j, 1);
617
                            }
618
                        }
619
                    }
620
                }
621
 
622
            });
623
 
624
            return availHandle;
625
        },
626
 
627
        /**
628
         * Works the same way as onAvailable, but additionally checks the
629
         * state of sibling elements to determine if the content of the
630
         * available element is safe to modify.
631
         *
632
         * <p>The callback is executed with a single parameter:
633
         * the custom object parameter, if provided.</p>
634
         *
635
         * @method onContentReady
636
         *
637
         * @param {string}   id the id of the element to look for.
638
         * @param {function} fn what to execute when the element is ready.
639
         * @param {object}   obj an optional object to be passed back as
640
         *                   a parameter to fn.
641
         * @param {boolean|object}  override If set to true, fn will execute
642
         *                   in the context of p_obj.  If an object, fn will
643
         *                   exectute in the context of that object
644
         *
645
         * @static
646
         * @deprecated Use Y.on("contentready")
647
         */
648
        // @TODO fix arguments
649
        onContentReady: function(id, fn, obj, override, compat) {
650
            return Event.onAvailable(id, fn, obj, override, true, compat);
651
        },
652
 
653
        /**
654
         * Adds an event listener
655
         *
656
         * @method attach
657
         *
658
         * @param {String}   type     The type of event to append
659
         * @param {Function} fn        The method the event invokes
660
         * @param {String|HTMLElement|Array|NodeList} el An id, an element
661
         *  reference, or a collection of ids and/or elements to assign the
662
         *  listener to.
663
         * @param {Object}   context optional context object
664
         * @param {Boolean|object}  args 0..n arguments to pass to the callback
665
         * @return {EventHandle} an object to that can be used to detach the listener
666
         *
667
         * @static
668
         */
669
 
670
        attach: function(type, fn, el, context) {
671
            return Event._attach(Y.Array(arguments, 0, true));
672
        },
673
 
674
        _createWrapper: function (el, type, capture, compat, facade) {
675
 
676
            var cewrapper,
677
                ek  = Y.stamp(el),
678
                key = 'event:' + ek + type;
679
 
680
            if (false === facade) {
681
                key += 'native';
682
            }
683
            if (capture) {
684
                key += 'capture';
685
            }
686
 
687
 
688
            cewrapper = _wrappers[key];
689
 
690
 
691
            if (!cewrapper) {
692
                // create CE wrapper
693
                cewrapper = Y.publish(key, {
694
                    silent: true,
695
                    bubbles: false,
696
                    emitFacade:false,
697
                    contextFn: function() {
698
                        if (compat) {
699
                            return cewrapper.el;
700
                        } else {
701
                            cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
702
                            return cewrapper.nodeRef;
703
                        }
704
                    }
705
                });
706
 
707
                cewrapper.overrides = {};
708
 
709
                // for later removeListener calls
710
                cewrapper.el = el;
711
                cewrapper.key = key;
712
                cewrapper.domkey = ek;
713
                cewrapper.type = type;
714
                cewrapper.fn = function(e) {
715
                    cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
716
                };
717
                cewrapper.capture = capture;
718
 
719
                if (el == win && type == "load") {
720
                    // window load happens once
721
                    cewrapper.fireOnce = true;
722
                    _windowLoadKey = key;
723
                }
724
                cewrapper._delete = _deleteAndClean;
725
 
726
                _wrappers[key] = cewrapper;
727
                _el_events[ek] = _el_events[ek] || {};
728
                _el_events[ek][key] = cewrapper;
729
 
730
                add(el, type, cewrapper.fn, capture);
731
            }
732
 
733
            return cewrapper;
734
 
735
        },
736
 
737
        _attach: function(args, conf) {
738
 
739
            var compat,
740
                handles, oEl, cewrapper, context,
741
                fireNow = false, ret,
742
                type = args[0],
743
                fn = args[1],
744
                el = args[2] || win,
745
                facade = conf && conf.facade,
746
                capture = conf && conf.capture,
747
                overrides = conf && conf.overrides;
748
 
749
            if (args[args.length-1] === COMPAT_ARG) {
750
                compat = true;
751
            }
752
 
753
            if (!fn || !fn.call) {
754
                return false;
755
            }
756
 
757
            // The el argument can be an array of elements or element ids.
758
            if (shouldIterate(el)) {
759
 
760
                handles=[];
761
 
762
                Y.each(el, function(v, k) {
763
                    args[2] = v;
764
                    handles.push(Event._attach(args.slice(), conf));
765
                });
766
 
767
                // return (handles.length === 1) ? handles[0] : handles;
768
                return new Y.EventHandle(handles);
769
 
770
            // If the el argument is a string, we assume it is
771
            // actually the id of the element.  If the page is loaded
772
            // we convert el to the actual element, otherwise we
773
            // defer attaching the event until the element is
774
            // ready
775
            } else if (Y.Lang.isString(el)) {
776
 
777
                // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
778
 
779
                if (compat) {
780
                    oEl = Y.DOM.byId(el);
781
                } else {
782
 
783
                    oEl = Y.Selector.query(el);
784
 
785
                    switch (oEl.length) {
786
                        case 0:
787
                            oEl = null;
788
                            break;
789
                        case 1:
790
                            oEl = oEl[0];
791
                            break;
792
                        default:
793
                            args[2] = oEl;
794
                            return Event._attach(args, conf);
795
                    }
796
                }
797
 
798
                if (oEl) {
799
 
800
                    el = oEl;
801
 
802
                // Not found = defer adding the event until the element is available
803
                } else {
804
 
805
                    ret = Event.onAvailable(el, function() {
806
 
807
                        ret.handle = Event._attach(args, conf);
808
 
809
                    }, Event, true, false, compat);
810
 
811
                    return ret;
812
 
813
                }
814
            }
815
 
816
            // Element should be an html element or node
817
            if (!el) {
818
                return false;
819
            }
820
 
821
            if (Y.Node && Y.instanceOf(el, Y.Node)) {
822
                el = Y.Node.getDOMNode(el);
823
            }
824
 
825
            cewrapper = Event._createWrapper(el, type, capture, compat, facade);
826
            if (overrides) {
827
                Y.mix(cewrapper.overrides, overrides);
828
            }
829
 
830
            if (el == win && type == "load") {
831
 
832
                // if the load is complete, fire immediately.
833
                // all subscribers, including the current one
834
                // will be notified.
835
                if (YUI.Env.windowLoaded) {
836
                    fireNow = true;
837
                }
838
            }
839
 
840
            if (compat) {
841
                args.pop();
842
            }
843
 
844
            context = args[3];
845
 
846
            // set context to the Node if not specified
847
            // ret = cewrapper.on.apply(cewrapper, trimmedArgs);
848
            ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
849
 
850
            if (fireNow) {
851
                cewrapper.fire();
852
            }
853
 
854
            return ret;
855
 
856
        },
857
 
858
        /**
859
         * Removes an event listener.  Supports the signature the event was bound
860
         * with, but the preferred way to remove listeners is using the handle
861
         * that is returned when using Y.on
862
         *
863
         * @method detach
864
         *
865
         * @param {String} type the type of event to remove.
866
         * @param {Function} fn the method the event invokes.  If fn is
867
         * undefined, then all event handlers for the type of event are
868
         * removed.
869
         * @param {String|HTMLElement|Array|NodeList|EventHandle} el An
870
         * event handle, an id, an element reference, or a collection
871
         * of ids and/or elements to remove the listener from.
872
         * @return {boolean} true if the unbind was successful, false otherwise.
873
         * @static
874
         */
875
        detach: function(type, fn, el, obj) {
876
 
877
            var args=Y.Array(arguments, 0, true), compat, l, ok, i,
878
                id, ce;
879
 
880
            if (args[args.length-1] === COMPAT_ARG) {
881
                compat = true;
882
                // args.pop();
883
            }
884
 
885
            if (type && type.detach) {
886
                return type.detach();
887
            }
888
 
889
            // The el argument can be a string
890
            if (typeof el == "string") {
891
 
892
                // el = (compat) ? Y.DOM.byId(el) : Y.all(el);
893
                if (compat) {
894
                    el = Y.DOM.byId(el);
895
                } else {
896
                    el = Y.Selector.query(el);
897
                    l = el.length;
898
                    if (l < 1) {
899
                        el = null;
900
                    } else if (l == 1) {
901
                        el = el[0];
902
                    }
903
                }
904
                // return Event.detach.apply(Event, args);
905
            }
906
 
907
            if (!el) {
908
                return false;
909
            }
910
 
911
            if (el.detach) {
912
                args.splice(2, 1);
913
                return el.detach.apply(el, args);
914
            // The el argument can be an array of elements or element ids.
915
            } else if (shouldIterate(el)) {
916
                ok = true;
917
                for (i=0, l=el.length; i<l; ++i) {
918
                    args[2] = el[i];
919
                    ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
920
                }
921
 
922
                return ok;
923
            }
924
 
925
            if (!type || !fn || !fn.call) {
926
                return Event.purgeElement(el, false, type);
927
            }
928
 
929
            id = 'event:' + Y.stamp(el) + type;
930
            ce = _wrappers[id];
931
 
932
            if (ce) {
933
                return ce.detach(fn);
934
            } else {
935
                return false;
936
            }
937
 
938
        },
939
 
940
        /**
941
         * Finds the event in the window object, the caller's arguments, or
942
         * in the arguments of another method in the callstack.  This is
943
         * executed automatically for events registered through the event
944
         * manager, so the implementer should not normally need to execute
945
         * this function at all.
946
         * @method getEvent
947
         * @param {Event} e the event parameter from the handler
948
         * @param {HTMLElement} el the element the listener was attached to
949
         * @return {Event} the event
950
         * @static
951
         */
952
        getEvent: function(e, el, noFacade) {
953
            var ev = e || win.event;
954
 
955
            return (noFacade) ? ev :
956
                new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
957
        },
958
 
959
        /**
960
         * Generates an unique ID for the element if it does not already
961
         * have one.
962
         * @method generateId
963
         * @param el the element to create the id for
964
         * @return {string} the resulting id of the element
965
         * @static
966
         */
967
        generateId: function(el) {
968
            return Y.DOM.generateID(el);
969
        },
970
 
971
        /**
972
         * We want to be able to use getElementsByTagName as a collection
973
         * to attach a group of events to.  Unfortunately, different
974
         * browsers return different types of collections.  This function
975
         * tests to determine if the object is array-like.  It will also
976
         * fail if the object is an array, but is empty.
977
         * @method _isValidCollection
978
         * @param o the object to test
979
         * @return {boolean} true if the object is array-like and populated
980
         * @deprecated was not meant to be used directly
981
         * @static
982
         * @private
983
         */
984
        _isValidCollection: shouldIterate,
985
 
986
        /**
987
         * hook up any deferred listeners
988
         * @method _load
989
         * @static
990
         * @private
991
         */
992
        _load: function(e) {
993
            if (!_loadComplete) {
994
                _loadComplete = true;
995
 
996
                // Just in case DOMReady did not go off for some reason
997
                // E._ready();
998
                if (Y.fire) {
999
                    Y.fire(EVENT_READY);
1000
                }
1001
 
1002
                // Available elements may not have been detected before the
1003
                // window load event fires. Try to find them now so that the
1004
                // the user is more likely to get the onAvailable notifications
1005
                // before the window load notification
1006
                Event._poll();
1007
            }
1008
        },
1009
 
1010
        /**
1011
         * Polling function that runs before the onload event fires,
1012
         * attempting to attach to DOM Nodes as soon as they are
1013
         * available
1014
         * @method _poll
1015
         * @static
1016
         * @private
1017
         */
1018
        _poll: function() {
1019
            if (Event.locked) {
1020
                return;
1021
            }
1022
 
1023
            if (Y.UA.ie && !YUI.Env.DOMReady) {
1024
                // Hold off if DOMReady has not fired and check current
1025
                // readyState to protect against the IE operation aborted
1026
                // issue.
1027
                Event.startInterval();
1028
                return;
1029
            }
1030
 
1031
            Event.locked = true;
1032
 
1033
            // keep trying until after the page is loaded.  We need to
1034
            // check the page load state prior to trying to bind the
1035
            // elements so that we can be certain all elements have been
1036
            // tested appropriately
1037
            var i, len, item, el, notAvail, executeItem,
1038
                tryAgain = !_loadComplete;
1039
 
1040
            if (!tryAgain) {
1041
                tryAgain = (_retryCount > 0);
1042
            }
1043
 
1044
            // onAvailable
1045
            notAvail = [];
1046
 
1047
            executeItem = function (el, item) {
1048
                var context, ov = item.override;
1049
                try {
1050
                    if (item.compat) {
1051
                        if (item.override) {
1052
                            if (ov === true) {
1053
                                context = item.obj;
1054
                            } else {
1055
                                context = ov;
1056
                            }
1057
                        } else {
1058
                            context = el;
1059
                        }
1060
                        item.fn.call(context, item.obj);
1061
                    } else {
1062
                        context = item.obj || Y.one(el);
1063
                        item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
1064
                    }
1065
                } catch (e) {
1066
                }
1067
            };
1068
 
1069
            // onAvailable
1070
            for (i=0,len=_avail.length; i<len; ++i) {
1071
                item = _avail[i];
1072
                if (item && !item.checkReady) {
1073
 
1074
                    // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1075
                    el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1076
 
1077
                    if (el) {
1078
                        executeItem(el, item);
1079
                        _avail[i] = null;
1080
                    } else {
1081
                        notAvail.push(item);
1082
                    }
1083
                }
1084
            }
1085
 
1086
            // onContentReady
1087
            for (i=0,len=_avail.length; i<len; ++i) {
1088
                item = _avail[i];
1089
                if (item && item.checkReady) {
1090
 
1091
                    // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1092
                    el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1093
 
1094
                    if (el) {
1095
                        // The element is available, but not necessarily ready
1096
                        // @todo should we test parentNode.nextSibling?
1097
                        if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
1098
                            executeItem(el, item);
1099
                            _avail[i] = null;
1100
                        }
1101
                    } else {
1102
                        notAvail.push(item);
1103
                    }
1104
                }
1105
            }
1106
 
1107
            _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
1108
 
1109
            if (tryAgain) {
1110
                // we may need to strip the nulled out items here
1111
                Event.startInterval();
1112
            } else {
1113
                clearInterval(Event._interval);
1114
                Event._interval = null;
1115
            }
1116
 
1117
            Event.locked = false;
1118
 
1119
            return;
1120
 
1121
        },
1122
 
1123
        /**
1124
         * Removes all listeners attached to the given element via addListener.
1125
         * Optionally, the node's children can also be purged.
1126
         * Optionally, you can specify a specific type of event to remove.
1127
         * @method purgeElement
1128
         * @param {HTMLElement} el the element to purge
1129
         * @param {boolean} recurse recursively purge this element's children
1130
         * as well.  Use with caution.
1131
         * @param {string} type optional type of listener to purge. If
1132
         * left out, all listeners will be removed
1133
         * @static
1134
         */
1135
        purgeElement: function(el, recurse, type) {
1136
            // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
1137
            var oEl = (Y.Lang.isString(el)) ?  Y.Selector.query(el, null, true) : el,
1138
                lis = Event.getListeners(oEl, type), i, len, children, child;
1139
 
1140
            if (recurse && oEl) {
1141
                lis = lis || [];
1142
                children = Y.Selector.query('*', oEl);
1143
                len = children.length;
1144
                for (i = 0; i < len; ++i) {
1145
                    child = Event.getListeners(children[i], type);
1146
                    if (child) {
1147
                        lis = lis.concat(child);
1148
                    }
1149
                }
1150
            }
1151
 
1152
            if (lis) {
1153
                for (i = 0, len = lis.length; i < len; ++i) {
1154
                    lis[i].detachAll();
1155
                }
1156
            }
1157
 
1158
        },
1159
 
1160
        /**
1161
         * Removes all object references and the DOM proxy subscription for
1162
         * a given event for a DOM node.
1163
         *
1164
         * @method _clean
1165
         * @param wrapper {CustomEvent} Custom event proxy for the DOM
1166
         *                  subscription
1167
         * @private
1168
         * @static
1169
         * @since 3.4.0
1170
         */
1171
        _clean: function (wrapper) {
1172
            var key    = wrapper.key,
1173
                domkey = wrapper.domkey;
1174
 
1175
            remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture);
1176
            delete _wrappers[key];
1177
            delete Y._yuievt.events[key];
1178
            if (_el_events[domkey]) {
1179
                delete _el_events[domkey][key];
1180
                if (!Y.Object.size(_el_events[domkey])) {
1181
                    delete _el_events[domkey];
1182
                }
1183
            }
1184
        },
1185
 
1186
        /**
1187
         * Returns all listeners attached to the given element via addListener.
1188
         * Optionally, you can specify a specific type of event to return.
1189
         * @method getListeners
1190
         * @param el {HTMLElement|string} the element or element id to inspect
1191
         * @param type {string} optional type of listener to return. If
1192
         * left out, all listeners will be returned
1193
         * @return {CustomEvent} the custom event wrapper for the DOM event(s)
1194
         * @static
1195
         */
1196
        getListeners: function(el, type) {
1197
            var ek = Y.stamp(el, true), evts = _el_events[ek],
1198
                results=[] , key = (type) ? 'event:' + ek + type : null,
1199
                adapters = _eventenv.plugins;
1200
 
1201
            if (!evts) {
1202
                return null;
1203
            }
1204
 
1205
            if (key) {
1206
                // look for synthetic events
1207
                if (adapters[type] && adapters[type].eventDef) {
1208
                    key += '_synth';
1209
                }
1210
 
1211
                if (evts[key]) {
1212
                    results.push(evts[key]);
1213
                }
1214
 
1215
                // get native events as well
1216
                key += 'native';
1217
                if (evts[key]) {
1218
                    results.push(evts[key]);
1219
                }
1220
 
1221
            } else {
1222
                Y.each(evts, function(v, k) {
1223
                    results.push(v);
1224
                });
1225
            }
1226
 
1227
            return (results.length) ? results : null;
1228
        },
1229
 
1230
        /**
1231
         * Removes all listeners registered by pe.event.  Called
1232
         * automatically during the unload event.
1233
         * @method _unload
1234
         * @static
1235
         * @private
1236
         */
1237
        _unload: function(e) {
1238
            Y.each(_wrappers, function(v, k) {
1239
                if (v.type == 'unload') {
1240
                    v.fire(e);
1241
                }
1242
                v.detachAll();
1243
            });
1244
            remove(win, "unload", onUnload);
1245
        },
1246
 
1247
        /**
1248
         * Adds a DOM event directly without the caching, cleanup, context adj, etc
1249
         *
1250
         * @method nativeAdd
1251
         * @param {HTMLElement} el      the element to bind the handler to
1252
         * @param {string}      type   the type of event handler
1253
         * @param {function}    fn      the callback to invoke
1254
         * @param {Boolean}      capture capture or bubble phase
1255
         * @static
1256
         * @private
1257
         */
1258
        nativeAdd: add,
1259
 
1260
        /**
1261
         * Basic remove listener
1262
         *
1263
         * @method nativeRemove
1264
         * @param {HTMLElement} el      the element to bind the handler to
1265
         * @param {string}      type   the type of event handler
1266
         * @param {function}    fn      the callback to invoke
1267
         * @param {Boolean}      capture capture or bubble phase
1268
         * @static
1269
         * @private
1270
         */
1271
        nativeRemove: remove
1272
    };
1273
 
1274
}();
1275
 
1276
Y.Event = Event;
1277
 
1278
if (config.injected || YUI.Env.windowLoaded) {
1279
    onLoad();
1280
} else {
1281
    add(win, "load", onLoad);
1282
}
1283
 
1284
// Process onAvailable/onContentReady items when when the DOM is ready in IE
1285
if (Y.UA.ie) {
1286
    Y.on(EVENT_READY, Event._poll);
1287
 
1288
    // In IE6 and below, detach event handlers when the page is unloaded in
1289
    // order to try and prevent cross-page memory leaks. This isn't done in
1290
    // other browsers because a) it's not necessary, and b) it breaks the
1291
    // back/forward cache.
1292
    if (Y.UA.ie < 7) {
1293
        try {
1294
            add(win, "unload", onUnload);
1295
        } catch(e) {
1296
        }
1297
    }
1298
}
1299
 
1300
Event.Custom = Y.CustomEvent;
1301
Event.Subscriber = Y.Subscriber;
1302
Event.Target = Y.EventTarget;
1303
Event.Handle = Y.EventHandle;
1304
Event.Facade = Y.EventFacade;
1305
 
1306
Event._poll();
1307
 
1308
}());
1309
 
1310
/**
1311
 * DOM event listener abstraction layer
1312
 * @module event
1313
 * @submodule event-base
1314
 */
1315
 
1316
/**
1317
 * Executes the callback as soon as the specified element
1318
 * is detected in the DOM.  This function expects a selector
1319
 * string for the element(s) to detect.  If you already have
1320
 * an element reference, you don't need this event.
1321
 * @event available
1322
 * @param type {string} 'available'
1323
 * @param fn {function} the callback function to execute.
1324
 * @param el {string} an selector for the element(s) to attach
1325
 * @param context optional argument that specifies what 'this' refers to.
1326
 * @param args* 0..n additional arguments to pass on to the callback function.
1327
 * These arguments will be added after the event object.
1328
 * @return {EventHandle} the detach handle
1329
 * @for YUI
1330
 */
1331
Y.Env.evt.plugins.available = {
1332
    on: function(type, fn, id, o) {
1333
        var a = arguments.length > 4 ?  Y.Array(arguments, 4, true) : null;
1334
        return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
1335
    }
1336
};
1337
 
1338
/**
1339
 * Executes the callback as soon as the specified element
1340
 * is detected in the DOM with a nextSibling property
1341
 * (indicating that the element's children are available).
1342
 * This function expects a selector
1343
 * string for the element(s) to detect.  If you already have
1344
 * an element reference, you don't need this event.
1345
 * @event contentready
1346
 * @param type {string} 'contentready'
1347
 * @param fn {function} the callback function to execute.
1348
 * @param el {string} an selector for the element(s) to attach.
1349
 * @param context optional argument that specifies what 'this' refers to.
1350
 * @param args* 0..n additional arguments to pass on to the callback function.
1351
 * These arguments will be added after the event object.
1352
 * @return {EventHandle} the detach handle
1353
 * @for YUI
1354
 */
1355
Y.Env.evt.plugins.contentready = {
1356
    on: function(type, fn, id, o) {
1357
        var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
1358
        return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
1359
    }
1360
};
1361
 
1362
 
1363
}, '3.18.1', {"requires": ["event-custom-base"]});