PluginProbe
Boxzilla – WordPress Popup Builder / 3.0.1
Boxzilla – WordPress Popup Builder v3.0.1
3.4.11 3.4.10 3.4.9 3.4.3 3.4.4 3.4.5 3.4.6 3.4.7 3.4.8 trunk 3.0 3.0.1 3.0.2 3.0.3 3.1 3.1.1 3.1.10 3.1.11 3.1.12 3.1.13 3.1.14 3.1.15 3.1.16 3.1.17 3.1.18 All 72 releases
boxzilla / assets / js / script.js

script.js in Boxzilla – WordPress Popup Builder 3.0.1, at assets/js/script.js

1,139 lines 35.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function () { var require = undefined; var define = undefined; (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2 'use strict';
3
4 var Boxzilla = require('boxzilla');
5 var options = window.boxzilla_options;
6 var isLoggedIn = document.body.className.indexOf('logged-in') > -1;
7
8 // print message when test mode is enabled
9 if( isLoggedIn && options.testMode ) {
10 console.log( 'Boxzilla: Test mode is enabled. Please disable test mode if you\'re done testing.' );
11 }
12
13 // init boxzilla
14 Boxzilla.init();
15
16 // create boxes from options
17 for( var i=0; i < options.boxes.length; i++ ) {
18 // get opts
19 var boxOpts = options.boxes[i];
20 boxOpts.testMode = isLoggedIn && options.testMode;
21
22 // create box
23 var box = Boxzilla.create( boxOpts.id, boxOpts);
24
25 // add custom css to box
26 css(box.element, boxOpts.css);
27 }
28
29 function css(element, styles) {
30 if( styles.background_color ) {
31 element.style.background = styles.background_color;
32 }
33
34 if( styles.color ) {
35 element.style.color = styles.color;
36 }
37
38 if( styles.border_color ) {
39 element.style.borderColor = styles.border_color;
40 }
41
42 if( styles.border_width ) {
43 element.style.borderWidth = parseInt(styles.border_width) + "px";
44 }
45
46 if( styles.border_style ) {
47 element.style.borderStyle = styles.border_style;
48 }
49
50 if( styles.width ) {
51 element.style.maxWidth = parseInt(styles.width) + "px";
52 }
53 }
54
55 window.Boxzilla = Boxzilla;
56 },{"boxzilla":3}],2:[function(require,module,exports){
57 'use strict';
58
59 var $ = window.jQuery,
60 defaults = {
61 'animation': 'fade',
62 'rehide': false,
63 'content': '',
64 'cookieTime': 0,
65 'icon': '&times',
66 'minimumScreenWidth': 0,
67 'position': 'center',
68 'testMode': false,
69 'trigger': false,
70 'closable': true
71 }, Boxzilla;
72
73 /**
74 * Merge 2 objects, values of the latter overwriting the former.
75 *
76 * @param obj1
77 * @param obj2
78 * @returns {*}
79 */
80 function merge( obj1, obj2 ) {
81 var obj3 = {};
82 for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
83 for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
84 return obj3;
85 }
86
87 // Box Object
88 var Box = function( id, config ) {
89 this.id = id;
90
91 // store config values
92 this.config = merge(defaults, config);
93
94 // store ref to overlay
95 this.overlay = document.getElementById('boxzilla-overlay');
96
97 // state
98 this.visible = false;
99 this.closed = false;
100 this.triggered = false;
101 this.triggerHeight = 0;
102 this.cookieSet = false;
103
104 // if a trigger was given, calculate values once and store
105 if( this.config.trigger ) {
106 if( this.config.trigger.method === 'percentage' || this.config.trigger.method === 'element' ) {
107 this.triggerHeight = this.calculateTriggerHeight();
108 }
109
110 this.cookieSet = this.isCookieSet();
111 }
112
113 // create dom element for this box
114 this.element = this.dom();
115 this.$element = $(this.element);
116
117 // further initialise the box
118 this.events();
119 };
120
121 // initialise the box
122 Box.prototype.events = function() {
123 var box = this;
124
125 // attach event to "close" icon inside box
126 this.$element.find('.boxzilla-close-icon').click(box.dismiss.bind(this));
127
128 this.$element.on('click', 'a', function(e) {
129 Boxzilla.trigger('box.interactions.link', [ box, e.target ] );
130 });
131
132 this.$element.on('submit', 'form', function(e) {
133 box.setCookie();
134 Boxzilla.trigger('box.interactions.form', [ box, e.target ]);
135 });
136
137 // attach event to all links referring #boxzilla-{box_id}
138 $(document.body).on('click', 'a[href="#boxzilla-' + box.id + '"]', function() {
139 box.toggle();
140 return false;
141 });
142
143 // maybe show box right away
144 if( this.fits() && this.locationHashRefersBox() ) {
145 $(window).load(this.show.bind(this));
146 }
147
148 };
149
150 // generate dom elements for this box
151 Box.prototype.dom = function() {
152 var wrapper = document.createElement('div');
153 wrapper.className = 'boxzilla-container boxzilla-' + this.config.position + '-container';
154
155 var box = document.createElement('div');
156 box.className = 'boxzilla boxzilla-' + this.id + ' boxzilla-' + this.config.position;
157 box.style.display = 'none';
158 wrapper.appendChild(box);
159
160 var content = document.createElement('div');
161 content.className = 'boxzilla-content';
162 content.innerHTML = this.config.content;
163 box.appendChild(content);
164
165 // remove <script> from box content and append them to head
166 var scripts = content.querySelectorAll('script');
167 if(scripts.length) {
168 var script = document.createElement('script');
169 for( var i=0; i<scripts.length; i++ ) {
170 script.appendChild(document.createTextNode(scripts[i].text));
171 scripts[i].parentNode.removeChild(scripts[i]);
172 }
173 document.head.appendChild(script);
174 }
175
176 if( this.config.closable && this.config.icon ) {
177 var icon = document.createElement('span');
178 icon.className = "boxzilla-close-icon";
179 icon.innerHTML = this.config.icon;
180 box.appendChild(icon);
181 }
182
183 document.body.appendChild(wrapper);
184
185 return box;
186 };
187
188 // set (calculate) custom box styling depending on box options
189 Box.prototype.setCustomBoxStyling = function() {
190
191 // reset element to its initial state
192 this.element.style.overflowY = 'auto';
193 this.element.style.maxHeight = 'none';
194
195 // get new dimensions
196 var windowHeight = window.innerHeight;
197 var boxHeight = this.$element.outerHeight();
198
199 // add scrollbar to box and limit height
200 if( boxHeight > windowHeight ) {
201 this.element.style.maxHeight = windowHeight + "px";
202 this.element.style.overflowY = 'scroll';
203 }
204
205 // set new top margin for boxes which are centered
206 if( this.config.position === 'center' ) {
207 var newTopMargin = ( ( windowHeight - boxHeight ) / 2 );
208 newTopMargin = newTopMargin >= 0 ? newTopMargin : 0;
209 this.element.style.marginTop = newTopMargin + "px";
210 }
211
212 };
213
214 // toggle visibility of the box
215 Box.prototype.toggle = function(show) {
216
217 // revert visibility if no explicit argument is given
218 if( typeof( show ) === "undefined" ) {
219 show = ! this.visible;
220 }
221
222 // do nothing if element is being animated
223 if( this.$element.is(':animated') ) {
224 return false;
225 }
226
227 // is box already at desired visibility?
228 if( show === this.visible ) {
229 return false;
230 }
231
232 // if box should be hidden but is not closable, bail.
233 if( ! show && ! this.config.closable ) {
234 return false;
235 }
236
237 // set new visibility status
238 this.visible = show;
239
240 // calculate custom styling for which CSS is "too stupid"
241 this.setCustomBoxStyling();
242
243 // fadein / fadeout the overlay if position is "center"
244 if( this.config.position === 'center' ) {
245 $(this.overlay).fadeToggle('slow');
246 }
247
248 // trigger event
249 Boxzilla.trigger('box.' + ( show ? 'show' : 'hide' ), [ this ] );
250
251 // show or hide box using selected animation
252 if( this.config.animation === 'fade' ) {
253 this.$element.fadeToggle( 'slow' );
254 } else {
255 this.$element.slideToggle( 'slow' );
256 }
257
258 // // focus on first input field in box
259 // this.$element.find('input').first().focus();
260
261 return true;
262 };
263
264 // show the box
265 Box.prototype.show = function() {
266 return this.toggle(true);
267 };
268
269 // hide the box
270 Box.prototype.hide = function() {
271 return this.toggle(false);
272 };
273
274 // calculate trigger height
275 Box.prototype.calculateTriggerHeight = function() {
276 var triggerHeight = 0;
277
278 if( this.config.trigger.method === 'element' ) {
279 var $triggerElement = $(this.config.trigger.value).first();
280 triggerHeight = ( $triggerElement.length > 0 ) ? $triggerElement.offset().top : 0;
281 } else if( this.config.trigger.method === 'percentage' ) {
282 triggerHeight = ( this.config.trigger.value / 100 * $(document).height() );
283 }
284
285 return triggerHeight;
286 };
287
288 // set cookie that disables automatically showing the box
289 Box.prototype.setCookie = function() {
290 // do nothing if cookieTime evaluates to false
291 if(! this.config.cookieTime) {
292 return;
293 }
294
295 var expiryDate = new Date();
296 expiryDate.setDate( expiryDate.getDate() + this.config.cookieTime );
297 document.cookie = 'boxzilla_box_'+ this.id + '=true; expires='+ expiryDate.toUTCString() +'; path=/';
298 };
299
300 // checks whether window.location.hash equals the box element ID or that of any element inside the box
301 Box.prototype.locationHashRefersBox = function() {
302
303 if( ! window.location.hash || 0 === window.location.hash.length ) {
304 return false;
305 }
306
307 var elementId = window.location.hash.substring(1);
308 if( elementId === this.element.id ) {
309 return true;
310 } else if( this.element.querySelector('#' + elementId) ) {
311 return true;
312 }
313
314 return false;
315 };
316
317 Box.prototype.fits = function() {
318 if( this.config.minimumScreenWidth <= 0 ) {
319 return true;
320 }
321
322 return window.innerWidth > this.config.minimumScreenWidth
323 };
324
325 // is this box enabled?
326 Box.prototype.mayAutoShow = function() {
327
328 // don't show if box was closed (dismissed) before
329 if( this.closed ) {
330 return false;
331 }
332
333 // check if box fits on given minimum screen width
334 if( ! this.fits() ) {
335 return false;
336 }
337
338 // if trigger empty or error in calculating triggerHeight, return false
339 if( ! this.config.trigger ) {
340 return false;
341 }
342
343 // rely on cookie value (show if not set, don't show if set)
344 return ! this.cookieSet;
345 };
346
347 Box.prototype.mayRehide = function() {
348 return this.config.rehide && this.triggered;
349 };
350
351 Box.prototype.isCookieSet = function() {
352 // always show on test mode
353 if( this.config.testMode ) {
354 return false;
355 }
356
357 // check for cookie
358 if( ! this.config.cookieTime ) {
359 return false;
360 }
361
362 var cookieSet = document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + 'boxzilla_box_' + this.id + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1") === "true";
363 return cookieSet;
364
365 };
366
367 Box.prototype.trigger = function() {
368 var shown = this.show();
369 if( shown ) {
370 this.triggered = true;
371 }
372 };
373
374 Box.prototype.dismiss = function() {
375 this.hide();
376 this.setCookie();
377 this.closed = true;
378 Boxzilla.trigger('box.dismiss', [ this ]);
379 };
380
381 module.exports = function(_Boxzilla) {
382 Boxzilla = _Boxzilla;
383 return Box;
384 };
385 },{}],3:[function(require,module,exports){
386 'use strict';
387
388 var $ = window.jQuery,
389 EventEmitter = require('wolfy87-eventemitter'),
390 Boxzilla = Object.create(EventEmitter.prototype),
391 Box = require('./Box.js')(Boxzilla),
392 Timer = require('./Timer.js'),
393 boxes = {},
394 windowHeight = window.innerHeight,
395 overlay = document.createElement('div'),
396 exitIntentDelayTimer,
397 exitIntentTriggered,
398 siteTimer = new Timer(sessionStorage.getItem('boxzilla_timer') || 0),
399 pageTimer = new Timer(0),
400 pageViews = sessionStorage.getItem('boxzilla_pageviews') || 0;
401
402 function each( obj, callback ) {
403 for( var key in obj ) {
404 if(! obj.hasOwnProperty(key)) continue;
405 callback(obj[key]);
406 }
407 }
408
409 function throttle(fn, threshhold, scope) {
410 threshhold || (threshhold = 250);
411 var last,
412 deferTimer;
413 return function () {
414 var context = scope || this;
415
416 var now = +new Date,
417 args = arguments;
418 if (last && now < last + threshhold) {
419 // hold on to it
420 clearTimeout(deferTimer);
421 deferTimer = setTimeout(function () {
422 last = now;
423 fn.apply(context, args);
424 }, threshhold);
425 } else {
426 last = now;
427 fn.apply(context, args);
428 }
429 };
430 }
431
432 // "keyup" listener
433 function onKeyUp(e) {
434 if (e.keyCode == 27) {
435 Boxzilla.dismiss();
436 }
437 }
438
439 // check "pageviews" criteria for each box
440 function checkPageViewsCriteria() {
441 each(boxes, function(box) {
442 if( ! box.mayAutoShow() ) {
443 return;
444 }
445
446 if( box.config.trigger.method === 'pageviews' && pageViews >= box.config.trigger.value ) {
447 box.trigger();
448 }
449 });
450 }
451
452 // check time trigger criteria for each box
453 function checkTimeCriteria() {
454 each(boxes, function(box) {
455 if( ! box.mayAutoShow() ) {
456 return;
457 }
458
459 // check "time on site" trigger
460 if (box.config.trigger.method === 'time_on_site' && siteTimer.time >= box.config.trigger.value) {
461 box.trigger();
462 }
463
464 // check "time on page" trigger
465 if (box.config.trigger.method === 'time_on_page' && pageTimer.time >= box.config.trigger.value) {
466 box.trigger();
467 }
468 });
469 }
470
471 // check triggerHeight criteria for all boxes
472 function checkHeightCriteria() {
473 var scrollY = window.scrollY;
474 var scrollHeight = scrollY + ( windowHeight * 0.9 );
475
476 each(boxes, function(box) {
477 if( ! box.mayAutoShow() || box.triggerHeight <= 0 ) {
478 return;
479 }
480
481 if( scrollHeight > box.triggerHeight ) {
482 box.trigger();
483 } else if( box.mayRehide() ) {
484 box.hide();
485 }
486 });
487 }
488
489 // recalculate heights and variables based on height
490 function recalculateHeights() {
491 windowHeight = window.innerHeight;
492
493 each(boxes, function(box) {
494 box.setCustomBoxStyling();
495 });
496 }
497
498 function onOverlayClick(e) {
499 var x = e.offsetX;
500 var y = e.offsetY;
501
502 // calculate if click was near a box to avoid closing it (click error margin)
503 each(boxes, function(box) {
504 var rect = box.element.getBoundingClientRect();
505 var margin = 100 + ( window.innerWidth * 0.05 );
506
507 // if click was not anywhere near box, dismiss it.
508 if( x < ( rect.left - margin ) || x > ( rect.right + margin ) || y < ( rect.top - margin ) || y > ( rect.bottom + margin ) ) {
509 box.dismiss();
510 }
511 });
512 }
513
514 function triggerExitIntent() {
515 if(exitIntentTriggered) return;
516
517 each(boxes, function(box) {
518 if(box.mayAutoShow() && box.config.trigger.method === 'exit_intent' ) {
519 box.trigger();
520 }
521 });
522
523 exitIntentTriggered = true;
524 }
525
526 function onMouseLeave(e) {
527 var delay = 400;
528
529 // did mouse leave at top of window?
530 if( e.clientY <= 0 ) {
531 exitIntentDelayTimer = window.setTimeout(triggerExitIntent, delay);
532 }
533 }
534
535 function onMouseEnter() {
536 if( exitIntentDelayTimer ) {
537 window.clearInterval(exitIntentDelayTimer);
538 exitIntentDelayTimer = null;
539 }
540 }
541
542 var timers = {
543 start: function() {
544 var sessionTime = sessionStorage.getItem('boxzilla_timer');
545 if( sessionTime ) siteTimer.time = sessionTime;
546 siteTimer.start();
547 pageTimer.start();
548 },
549 stop: function() {
550 sessionStorage.setItem('boxzilla_timer', siteTimer.time);
551 siteTimer.stop();
552 pageTimer.stop();
553 }
554 };
555
556 // initialise & add event listeners
557 Boxzilla.init = function() {
558 var html = document.documentElement;
559
560 // add overlay element to dom
561 overlay.id = 'boxzilla-overlay';
562 document.body.appendChild(overlay);
563
564 // event binds
565 $(window).on('scroll', throttle(checkHeightCriteria));
566 $(window).on('resize', throttle(recalculateHeights));
567 $(window).on('load', recalculateHeights );
568 $(html).on('mouseleave', onMouseLeave);
569 $(html).on('mouseenter', onMouseEnter);
570 $(html).on('keyup', onKeyUp);
571 $(overlay).click(onOverlayClick);
572 window.setInterval(checkTimeCriteria, 1000);
573 window.setTimeout(checkPageViewsCriteria, 1000 );
574
575 timers.start();
576 $(window).on('focus', timers.start);
577 $(window).on('beforeunload', function() {
578 timers.stop();
579 sessionStorage.setItem('boxzilla_pageviews', ++pageViews);
580 });
581 $(window).on('blur', timers.stop);
582
583 Boxzilla.trigger('ready');
584 };
585
586 /**
587 * Create a new Box
588 *
589 * @param string id
590 * @param object opts
591 *
592 * @returns Box
593 */
594 Boxzilla.create = function(id, opts) {
595 boxes[id] = new Box(id, opts);
596 return boxes[id];
597 };
598
599 // dismiss a single box (or all by omitting id param)
600 Boxzilla.dismiss = function(id) {
601 // if no id given, dismiss all current open boxes
602 if( typeof(id) === "undefined" ) {
603 each(boxes, function(box) { box.dismiss(); });
604 } else if( typeof( boxes[id] ) === "object" ) {
605 boxes[id].dismiss();
606 }
607 };
608
609 Boxzilla.hide = function(id) {
610 if( typeof(id) === "undefined" ) {
611 each(boxes, function(box) { box.hide(); });
612 } else if( typeof( boxes[id] ) === "object" ) {
613 boxes[id].hide();
614 }
615 };
616
617 Boxzilla.show = function(id) {
618 if( typeof(id) === "undefined" ) {
619 each(boxes, function(box) { box.show(); });
620 } else if( typeof( boxes[id] ) === "object" ) {
621 boxes[id].show();
622 }
623 };
624
625 Boxzilla.toggle = function(id) {
626 if( typeof(id) === "undefined" ) {
627 each(boxes, function(box) { box.toggle(); });
628 } else if( typeof( boxes[id] ) === "object" ) {
629 boxes[id].toggle();
630 }
631 };
632
633 if ( typeof module !== 'undefined' && module.exports ) {
634 module.exports = Boxzilla;
635 } else {
636 this.Boxzilla = Boxzilla;
637 }
638 },{"./Box.js":2,"./Timer.js":4,"wolfy87-eventemitter":5}],4:[function(require,module,exports){
639 'use strict';
640
641 var Timer = function(start) {
642 this.time = start;
643 this.interval = 0;
644 };
645
646 Timer.prototype.tick = function() {
647 this.time++;
648 };
649
650 Timer.prototype.start = function() {
651 if( ! this.interval ) {
652 this.interval = window.setInterval(this.tick.bind(this), 1000);
653 }
654 };
655
656 Timer.prototype.stop = function() {
657 window.clearInterval(this.interval);
658 this.interval = 0;
659 };
660
661 module.exports = Timer;
662 },{}],5:[function(require,module,exports){
663 /*!
664 * EventEmitter v4.2.11 - git.io/ee
665 * Unlicense - http://unlicense.org/
666 * Oliver Caldwell - http://oli.me.uk/
667 * @preserve
668 */
669
670 ;(function () {
671 'use strict';
672
673 /**
674 * Class for managing events.
675 * Can be extended to provide event functionality in other classes.
676 *
677 * @class EventEmitter Manages event registering and emitting.
678 */
679 function EventEmitter() {}
680
681 // Shortcuts to improve speed and size
682 var proto = EventEmitter.prototype;
683 var exports = this;
684 var originalGlobalValue = exports.EventEmitter;
685
686 /**
687 * Finds the index of the listener for the event in its storage array.
688 *
689 * @param {Function[]} listeners Array of listeners to search through.
690 * @param {Function} listener Method to look for.
691 * @return {Number} Index of the specified listener, -1 if not found
692 * @api private
693 */
694 function indexOfListener(listeners, listener) {
695 var i = listeners.length;
696 while (i--) {
697 if (listeners[i].listener === listener) {
698 return i;
699 }
700 }
701
702 return -1;
703 }
704
705 /**
706 * Alias a method while keeping the context correct, to allow for overwriting of target method.
707 *
708 * @param {String} name The name of the target method.
709 * @return {Function} The aliased method
710 * @api private
711 */
712 function alias(name) {
713 return function aliasClosure() {
714 return this[name].apply(this, arguments);
715 };
716 }
717
718 /**
719 * Returns the listener array for the specified event.
720 * Will initialise the event object and listener arrays if required.
721 * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
722 * Each property in the object response is an array of listener functions.
723 *
724 * @param {String|RegExp} evt Name of the event to return the listeners from.
725 * @return {Function[]|Object} All listener functions for the event.
726 */
727 proto.getListeners = function getListeners(evt) {
728 var events = this._getEvents();
729 var response;
730 var key;
731
732 // Return a concatenated array of all matching events if
733 // the selector is a regular expression.
734 if (evt instanceof RegExp) {
735 response = {};
736 for (key in events) {
737 if (events.hasOwnProperty(key) && evt.test(key)) {
738 response[key] = events[key];
739 }
740 }
741 }
742 else {
743 response = events[evt] || (events[evt] = []);
744 }
745
746 return response;
747 };
748
749 /**
750 * Takes a list of listener objects and flattens it into a list of listener functions.
751 *
752 * @param {Object[]} listeners Raw listener objects.
753 * @return {Function[]} Just the listener functions.
754 */
755 proto.flattenListeners = function flattenListeners(listeners) {
756 var flatListeners = [];
757 var i;
758
759 for (i = 0; i < listeners.length; i += 1) {
760 flatListeners.push(listeners[i].listener);
761 }
762
763 return flatListeners;
764 };
765
766 /**
767 * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
768 *
769 * @param {String|RegExp} evt Name of the event to return the listeners from.
770 * @return {Object} All listener functions for an event in an object.
771 */
772 proto.getListenersAsObject = function getListenersAsObject(evt) {
773 var listeners = this.getListeners(evt);
774 var response;
775
776 if (listeners instanceof Array) {
777 response = {};
778 response[evt] = listeners;
779 }
780
781 return response || listeners;
782 };
783
784 /**
785 * Adds a listener function to the specified event.
786 * The listener will not be added if it is a duplicate.
787 * If the listener returns true then it will be removed after it is called.
788 * If you pass a regular expression as the event name then the listener will be added to all events that match it.
789 *
790 * @param {String|RegExp} evt Name of the event to attach the listener to.
791 * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
792 * @return {Object} Current instance of EventEmitter for chaining.
793 */
794 proto.addListener = function addListener(evt, listener) {
795 var listeners = this.getListenersAsObject(evt);
796 var listenerIsWrapped = typeof listener === 'object';
797 var key;
798
799 for (key in listeners) {
800 if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
801 listeners[key].push(listenerIsWrapped ? listener : {
802 listener: listener,
803 once: false
804 });
805 }
806 }
807
808 return this;
809 };
810
811 /**
812 * Alias of addListener
813 */
814 proto.on = alias('addListener');
815
816 /**
817 * Semi-alias of addListener. It will add a listener that will be
818 * automatically removed after its first execution.
819 *
820 * @param {String|RegExp} evt Name of the event to attach the listener to.
821 * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
822 * @return {Object} Current instance of EventEmitter for chaining.
823 */
824 proto.addOnceListener = function addOnceListener(evt, listener) {
825 return this.addListener(evt, {
826 listener: listener,
827 once: true
828 });
829 };
830
831 /**
832 * Alias of addOnceListener.
833 */
834 proto.once = alias('addOnceListener');
835
836 /**
837 * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
838 * You need to tell it what event names should be matched by a regex.
839 *
840 * @param {String} evt Name of the event to create.
841 * @return {Object} Current instance of EventEmitter for chaining.
842 */
843 proto.defineEvent = function defineEvent(evt) {
844 this.getListeners(evt);
845 return this;
846 };
847
848 /**
849 * Uses defineEvent to define multiple events.
850 *
851 * @param {String[]} evts An array of event names to define.
852 * @return {Object} Current instance of EventEmitter for chaining.
853 */
854 proto.defineEvents = function defineEvents(evts) {
855 for (var i = 0; i < evts.length; i += 1) {
856 this.defineEvent(evts[i]);
857 }
858 return this;
859 };
860
861 /**
862 * Removes a listener function from the specified event.
863 * When passed a regular expression as the event name, it will remove the listener from all events that match it.
864 *
865 * @param {String|RegExp} evt Name of the event to remove the listener from.
866 * @param {Function} listener Method to remove from the event.
867 * @return {Object} Current instance of EventEmitter for chaining.
868 */
869 proto.removeListener = function removeListener(evt, listener) {
870 var listeners = this.getListenersAsObject(evt);
871 var index;
872 var key;
873
874 for (key in listeners) {
875 if (listeners.hasOwnProperty(key)) {
876 index = indexOfListener(listeners[key], listener);
877
878 if (index !== -1) {
879 listeners[key].splice(index, 1);
880 }
881 }
882 }
883
884 return this;
885 };
886
887 /**
888 * Alias of removeListener
889 */
890 proto.off = alias('removeListener');
891
892 /**
893 * Adds listeners in bulk using the manipulateListeners method.
894 * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
895 * You can also pass it a regular expression to add the array of listeners to all events that match it.
896 * Yeah, this function does quite a bit. That's probably a bad thing.
897 *
898 * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
899 * @param {Function[]} [listeners] An optional array of listener functions to add.
900 * @return {Object} Current instance of EventEmitter for chaining.
901 */
902 proto.addListeners = function addListeners(evt, listeners) {
903 // Pass through to manipulateListeners
904 return this.manipulateListeners(false, evt, listeners);
905 };
906
907 /**
908 * Removes listeners in bulk using the manipulateListeners method.
909 * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
910 * You can also pass it an event name and an array of listeners to be removed.
911 * You can also pass it a regular expression to remove the listeners from all events that match it.
912 *
913 * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
914 * @param {Function[]} [listeners] An optional array of listener functions to remove.
915 * @return {Object} Current instance of EventEmitter for chaining.
916 */
917 proto.removeListeners = function removeListeners(evt, listeners) {
918 // Pass through to manipulateListeners
919 return this.manipulateListeners(true, evt, listeners);
920 };
921
922 /**
923 * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
924 * The first argument will determine if the listeners are removed (true) or added (false).
925 * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
926 * You can also pass it an event name and an array of listeners to be added/removed.
927 * You can also pass it a regular expression to manipulate the listeners of all events that match it.
928 *
929 * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
930 * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
931 * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
932 * @return {Object} Current instance of EventEmitter for chaining.
933 */
934 proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
935 var i;
936 var value;
937 var single = remove ? this.removeListener : this.addListener;
938 var multiple = remove ? this.removeListeners : this.addListeners;
939
940 // If evt is an object then pass each of its properties to this method
941 if (typeof evt === 'object' && !(evt instanceof RegExp)) {
942 for (i in evt) {
943 if (evt.hasOwnProperty(i) && (value = evt[i])) {
944 // Pass the single listener straight through to the singular method
945 if (typeof value === 'function') {
946 single.call(this, i, value);
947 }
948 else {
949 // Otherwise pass back to the multiple function
950 multiple.call(this, i, value);
951 }
952 }
953 }
954 }
955 else {
956 // So evt must be a string
957 // And listeners must be an array of listeners
958 // Loop over it and pass each one to the multiple method
959 i = listeners.length;
960 while (i--) {
961 single.call(this, evt, listeners[i]);
962 }
963 }
964
965 return this;
966 };
967
968 /**
969 * Removes all listeners from a specified event.
970 * If you do not specify an event then all listeners will be removed.
971 * That means every event will be emptied.
972 * You can also pass a regex to remove all events that match it.
973 *
974 * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
975 * @return {Object} Current instance of EventEmitter for chaining.
976 */
977 proto.removeEvent = function removeEvent(evt) {
978 var type = typeof evt;
979 var events = this._getEvents();
980 var key;
981
982 // Remove different things depending on the state of evt
983 if (type === 'string') {
984 // Remove all listeners for the specified event
985 delete events[evt];
986 }
987 else if (evt instanceof RegExp) {
988 // Remove all events matching the regex.
989 for (key in events) {
990 if (events.hasOwnProperty(key) && evt.test(key)) {
991 delete events[key];
992 }
993 }
994 }
995 else {
996 // Remove all listeners in all events
997 delete this._events;
998 }
999
1000 return this;
1001 };
1002
1003 /**
1004 * Alias of removeEvent.
1005 *
1006 * Added to mirror the node API.
1007 */
1008 proto.removeAllListeners = alias('removeEvent');
1009
1010 /**
1011 * Emits an event of your choice.
1012 * When emitted, every listener attached to that event will be executed.
1013 * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
1014 * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
1015 * So they will not arrive within the array on the other side, they will be separate.
1016 * You can also pass a regular expression to emit to all events that match it.
1017 *
1018 * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
1019 * @param {Array} [args] Optional array of arguments to be passed to each listener.
1020 * @return {Object} Current instance of EventEmitter for chaining.
1021 */
1022 proto.emitEvent = function emitEvent(evt, args) {
1023 var listenersMap = this.getListenersAsObject(evt);
1024 var listeners;
1025 var listener;
1026 var i;
1027 var key;
1028 var response;
1029
1030 for (key in listenersMap) {
1031 if (listenersMap.hasOwnProperty(key)) {
1032 listeners = listenersMap[key].slice(0);
1033 i = listeners.length;
1034
1035 while (i--) {
1036 // If the listener returns true then it shall be removed from the event
1037 // The function is executed either with a basic call or an apply if there is an args array
1038 listener = listeners[i];
1039
1040 if (listener.once === true) {
1041 this.removeListener(evt, listener.listener);
1042 }
1043
1044 response = listener.listener.apply(this, args || []);
1045
1046 if (response === this._getOnceReturnValue()) {
1047 this.removeListener(evt, listener.listener);
1048 }
1049 }
1050 }
1051 }
1052
1053 return this;
1054 };
1055
1056 /**
1057 * Alias of emitEvent
1058 */
1059 proto.trigger = alias('emitEvent');
1060
1061 /**
1062 * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
1063 * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
1064 *
1065 * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
1066 * @param {...*} Optional additional arguments to be passed to each listener.
1067 * @return {Object} Current instance of EventEmitter for chaining.
1068 */
1069 proto.emit = function emit(evt) {
1070 var args = Array.prototype.slice.call(arguments, 1);
1071 return this.emitEvent(evt, args);
1072 };
1073
1074 /**
1075 * Sets the current value to check against when executing listeners. If a
1076 * listeners return value matches the one set here then it will be removed
1077 * after execution. This value defaults to true.
1078 *
1079 * @param {*} value The new value to check for when executing listeners.
1080 * @return {Object} Current instance of EventEmitter for chaining.
1081 */
1082 proto.setOnceReturnValue = function setOnceReturnValue(value) {
1083 this._onceReturnValue = value;
1084 return this;
1085 };
1086
1087 /**
1088 * Fetches the current value to check against when executing listeners. If
1089 * the listeners return value matches this one then it should be removed
1090 * automatically. It will return true by default.
1091 *
1092 * @return {*|Boolean} The current value to check for or the default, true.
1093 * @api private
1094 */
1095 proto._getOnceReturnValue = function _getOnceReturnValue() {
1096 if (this.hasOwnProperty('_onceReturnValue')) {
1097 return this._onceReturnValue;
1098 }
1099 else {
1100 return true;
1101 }
1102 };
1103
1104 /**
1105 * Fetches the events object and creates one if required.
1106 *
1107 * @return {Object} The events storage object.
1108 * @api private
1109 */
1110 proto._getEvents = function _getEvents() {
1111 return this._events || (this._events = {});
1112 };
1113
1114 /**
1115 * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
1116 *
1117 * @return {Function} Non conflicting EventEmitter class.
1118 */
1119 EventEmitter.noConflict = function noConflict() {
1120 exports.EventEmitter = originalGlobalValue;
1121 return EventEmitter;
1122 };
1123
1124 // Expose the class either via AMD, CommonJS or the global object
1125 if (typeof define === 'function' && define.amd) {
1126 define(function () {
1127 return EventEmitter;
1128 });
1129 }
1130 else if (typeof module === 'object' && module.exports){
1131 module.exports = EventEmitter;
1132 }
1133 else {
1134 exports.EventEmitter = EventEmitter;
1135 }
1136 }.call(this));
1137
1138 },{}]},{},[1]);
1139 })();