How to use emitter method in storybook-root

Best JavaScript code snippet using storybook-root

event-emitter.test.js

Source:event-emitter.test.js Github

copy

Full Screen

1import { BaseError} from '../../src/core';2import BX from '../old/core/internal/bootstrap';3import { EventEmitter, BaseEvent} from 'main.core.events';4describe('EventEmitter', () => {5 it('Should be exported as function', () => {6 assert(typeof EventEmitter === 'function');7 });8 it('Should implement public interface', () => {9 const emitter = new EventEmitter();10 assert(typeof emitter.subscribe === 'function');11 assert(typeof emitter.subscribeOnce === 'function');12 assert(typeof emitter.emit === 'function');13 assert(typeof emitter.unsubscribe === 'function');14 assert(typeof emitter.getMaxListeners === 'function');15 assert(typeof emitter.setMaxListeners === 'function');16 assert(typeof emitter.getListeners === 'function');17 assert(typeof emitter.incrementMaxListeners === 'function');18 assert(typeof emitter.decrementMaxListeners === 'function');19 });20 describe('subscribe', () => {21 it('Should add event listener', () => {22 const emitter = new EventEmitter();23 const event = 'test:event';24 const listener1 = () => {};25 const listener2 = () => {};26 const listener3 = () => {};27 emitter.subscribe(event, listener1);28 emitter.subscribe(event, listener2);29 emitter.subscribe(event, listener3);30 assert.equal(emitter.getListeners(event).size, 3);31 });32 it('Should add unique listeners only', () => {33 const emitter = new EventEmitter();34 const event = 'test:event';35 const listener = () => {};36 const listener2 = () => {};37 const consoleError = sinon.spy(console, 'error');38 emitter.subscribe(event, listener);39 emitter.subscribe(event, listener);40 emitter.subscribe(event, listener);41 emitter.subscribe(event, listener);42 assert(consoleError.callCount === 3);43 emitter.subscribeOnce(event, listener);44 emitter.subscribeOnce(event, listener);45 emitter.subscribeOnce(event, listener);46 assert(consoleError.callCount === 6);47 emitter.subscribeOnce(event, listener2);48 emitter.subscribeOnce(event, listener2);49 emitter.subscribeOnce(event, listener2);50 emitter.subscribe(event, listener2);51 emitter.subscribe(event, listener2);52 assert(consoleError.callCount === 10);53 consoleError.restore();54 assert.equal(emitter.getListeners(event).size, 2);55 const obj = {};56 const once = sinon.stub();57 EventEmitter.subscribeOnce(obj, 'event:once', once);58 EventEmitter.emit(obj, 'event:once');59 EventEmitter.emit(obj, 'event:once');60 EventEmitter.emit(obj, 'event:once');61 assert.equal(once.callCount, 1);62 });63 });64 describe('unsubscribe', () => {65 it('Should remove specified event listener', () => {66 const emitter = new EventEmitter();67 const event = 'test:event';68 const listener1 = () => {};69 const listener2 = () => {};70 const listener3 = () => {};71 emitter.subscribe(event, listener1);72 emitter.subscribe(event, listener2);73 emitter.subscribe(event, listener3);74 emitter.unsubscribe(event, listener1);75 assert.equal(emitter.getListeners(event).size, 2);76 assert(emitter.getListeners(event).has(listener1) === false);77 assert(emitter.getListeners(event).has(listener2) === true);78 assert(emitter.getListeners(event).has(listener3) === true);79 });80 });81 describe('unsubscribeAll', () => {82 it('Should unsubscribe event listeners', () => {83 const emitter = new EventEmitter();84 const eventName = 'test:event';85 const listener1 = () => {};86 const listener2 = () => {};87 const listener3 = () => {};88 const listener4 = () => {};89 emitter.subscribe(eventName, listener1);90 emitter.subscribe(eventName, listener2);91 emitter.subscribe(eventName, listener3);92 emitter.subscribe(eventName + "2", listener4);93 assert.equal(emitter.getListeners(eventName).size, 3);94 emitter.unsubscribeAll(eventName);95 assert.equal(emitter.getListeners(eventName).size, 0);96 });97 it('Should unsubscribe all event listeners', () => {98 const emitter = new EventEmitter();99 const eventName = 'test:event';100 const eventName2 = 'test:event2';101 const listener1 = () => {};102 const listener2 = () => {};103 const listener3 = () => {};104 const listener4 = () => {};105 emitter.subscribe(eventName, listener1);106 emitter.subscribe(eventName, listener2);107 emitter.subscribe(eventName, listener3);108 emitter.subscribe(eventName2, listener1);109 emitter.subscribe(eventName2, listener2);110 emitter.subscribe(eventName2, listener3);111 emitter.subscribe(eventName2, listener4);112 assert.equal(emitter.getListeners(eventName).size, 3);113 assert.equal(emitter.getListeners(eventName2).size, 4);114 emitter.unsubscribeAll();115 assert.equal(emitter.getListeners(eventName).size, 0);116 assert.equal(emitter.getListeners(eventName2).size, 0);117 });118 });119 describe('emit', () => {120 it('Should call all event listeners', () => {121 const emitter = new EventEmitter();122 const event = 'test:event';123 const listener1 = sinon.stub();124 const listener2 = sinon.stub();125 const listener3 = sinon.stub();126 emitter.subscribe(event, listener1);127 emitter.subscribe(event, listener2);128 emitter.subscribe(event, listener3);129 emitter.emit(event);130 assert(listener1.calledOnce);131 assert(listener2.calledOnce);132 assert(listener3.calledOnce);133 });134 it('Should not call listener if was unsubscribe by a previous sibling listener', () => {135 const emitter = new EventEmitter();136 const eventName = 'event:sibling';137 let result = '';138 const listener1 = () => { result += "1"; };139 const listener2 = () => { result += "2"; emitter.unsubscribe(eventName, listener3)};140 const listener3 = () => { result += "3"; };141 emitter.subscribe(eventName, listener1);142 emitter.subscribe(eventName, listener2);143 emitter.subscribe(eventName, listener3);144 emitter.emit(eventName);145 assert.equal(result, '12');146 });147 it('Should execute listeners in a right sequence.', () => {148 let result = '';149 const listener1 = () => { result += "1"; };150 const listener2 = () => { result += "2"; };151 const listener3 = () => { result += "3"; };152 const listener4 = () => { result += "4"; };153 const listener5 = () => { result += "5"; };154 const emitter = new EventEmitter();155 const eventName = 'event:sequence';156 emitter.subscribe(eventName, listener1);157 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener2);158 emitter.subscribe(eventName, listener3);159 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener4);160 emitter.subscribe(eventName, listener5);161 emitter.emit(eventName);162 assert.equal(result, '12345');163 });164 it('Should call event listeners after each emit call', () => {165 const emitter = new EventEmitter();166 const event = 'test:event';167 const listener1 = sinon.stub();168 const listener2 = sinon.stub();169 const listener3 = sinon.stub();170 emitter.subscribe(event, listener1);171 emitter.subscribe(event, listener2);172 emitter.subscribe(event, listener3);173 emitter.emit(event);174 assert(listener1.callCount === 1);175 assert(listener2.callCount === 1);176 assert(listener3.callCount === 1);177 emitter.emit(event);178 assert(listener1.callCount === 2);179 assert(listener2.callCount === 2);180 assert(listener3.callCount === 2);181 emitter.emit(event);182 emitter.emit(event);183 emitter.emit(event);184 assert(listener1.callCount === 5);185 assert(listener2.callCount === 5);186 assert(listener3.callCount === 5);187 });188 it('Should not call deleted listeners', () => {189 const emitter = new EventEmitter();190 const event = 'test:event';191 const listener1 = sinon.stub();192 const listener2 = sinon.stub();193 const listener3 = sinon.stub();194 emitter.subscribe(event, listener1);195 emitter.subscribe(event, listener2);196 emitter.subscribe(event, listener3);197 emitter.emit(event);198 assert(listener1.callCount === 1);199 assert(listener2.callCount === 1);200 assert(listener3.callCount === 1);201 emitter.unsubscribe(event, listener1);202 emitter.emit(event);203 assert(listener1.callCount === 1);204 assert(listener2.callCount === 2);205 assert(listener3.callCount === 2);206 });207 it('Should call listener with valid Event object anyway', async () => {208 const emitter = new EventEmitter();209 const eventName = "test:event";210 await new Promise((resolve) => {211 emitter.subscribe(eventName, (event) => {212 assert(event instanceof BaseEvent);213 assert(event.type === eventName);214 assert(event.hasOwnProperty("data"));215 assert(event.defaultPrevented === false);216 assert(event.immediatePropagationStopped === false);217 assert(typeof event.preventDefault === 'function');218 assert(typeof event.stopImmediatePropagation === 'function');219 assert(typeof event.isImmediatePropagationStopped === 'function');220 resolve();221 });222 emitter.emit(eventName);223 });224 });225 it('Should assign props to data if passed plain object', async () => {226 const emitter = new EventEmitter();227 const eventName = "Test:event";228 await new Promise((resolve) => {229 emitter.subscribe(eventName, (event) => {230 assert(event.data.test1 === 1);231 assert(event.data.test2 === 2);232 resolve();233 });234 emitter.emit(eventName, {test1: 1, test2: 2});235 });236 });237 it('Should add event value to data.event.value if passed not event object and not plain object', async () => {238 const emitter = new EventEmitter();239 const eventName = "Test:event";240 await new Promise((resolve) => {241 emitter.subscribe(eventName, (event) => {242 assert(Array.isArray(event.data));243 assert(event.data[0] === 1);244 assert(event.data[1] === 2);245 resolve();246 });247 emitter.emit(eventName, [1, 2]);248 });249 await new Promise((resolve) => {250 emitter.subscribe(`${eventName}2`, (event) => {251 assert(typeof event.data === 'string');252 assert(event.data === 'test');253 resolve();254 });255 emitter.emit(`${eventName}2`, 'test');256 });257 await new Promise((resolve) => {258 emitter.subscribe(`${eventName}3`, (event) => {259 assert(typeof event.data === 'boolean');260 assert(event.data === true);261 resolve();262 });263 emitter.emit(`${eventName}3`, true);264 });265 });266/*267 it('Should set event.isTrusted = true if event emitted with instance method', async () => {268 class Emitter extends EventEmitter {}269 const emitter = new Emitter();270 await new Promise((resolve) => {271 emitter.subscribe("test", (event) => {272 assert(event.isTrusted === true);273 resolve();274 });275 emitter.emit("test");276 });277 });278 it('Should set event.isTrusted = false if event emitted with static method', async () => {279 class Emitter extends EventEmitter {}280 const emitter = new Emitter();281 await new Promise((resolve) => {282 emitter.subscribe("test2", (event) => {283 assert(event.isTrusted === false);284 resolve();285 });286 EventEmitter.emit("test2");287 });288 await new Promise((resolve) => {289 emitter.subscribe("test3", (event) => {290 assert(event.isTrusted === false);291 resolve();292 });293 Emitter.emit("test3");294 });295 });296*/297 it('Should set defaultPrevented = true called .preventDefault() in listener', async () => {298 const emitter = new EventEmitter();299 emitter.subscribe('test4', (event) => {300 event.preventDefault();301 });302 const event = new BaseEvent();303 emitter.emit('test4', event);304 assert(event.isDefaultPrevented() === true);305 assert(event.defaultPrevented === true);306 });307 it('Should set thisArg for listeners', (done) => {308 const eventName = 'My:EventName';309 const obj = {};310 const thisArg = { a: 1 };311 BX.addCustomEvent(eventName, function() {312 assert.equal(this, thisArg);313 });314 EventEmitter.subscribe(eventName, function() {315 assert.equal(this, thisArg);316 done();317 });318 EventEmitter.emit(obj, eventName, {}, { thisArg });319 });320 });321 describe('emitAsync', () => {322 it('Should emit event and return promise', () => {323 const emitter = new EventEmitter();324 const resultPromise = emitter.emitAsync('test');325 assert.ok(resultPromise instanceof Promise);326 });327 it('Should resolve returned promise with values that returned from listeners', () => {328 const emitter = new EventEmitter();329 emitter.subscribe('test', () => {330 return 'result-1';331 });332 emitter.subscribe('test', () => {333 return true;334 });335 emitter.subscribe('test', () => {336 return 'test-result-3';337 });338 return emitter339 .emitAsync('test')340 .then((results) => {341 assert.ok(results[0] === 'result-1');342 assert.ok(results[1] === true);343 assert.ok(results[2] === 'test-result-3');344 });345 });346 it('Promise should be resolved, when resolved all promises returned from listeners', () => {347 const emitter = new EventEmitter();348 emitter.subscribe('test', () => {349 return new Promise((resolve) => {350 setTimeout(() => {351 resolve('value1');352 }, 500);353 });354 });355 emitter.subscribe('test', () => {356 return new Promise((resolve) => {357 setTimeout(() => {358 resolve('value2');359 }, 700);360 });361 });362 emitter.subscribe('test', () => {363 return new Promise((resolve) => {364 setTimeout(() => {365 resolve('value3');366 }, 900);367 });368 });369 return emitter370 .emitAsync('test')371 .then((results) => {372 assert.ok(results[0] === 'value1');373 assert.ok(results[1] === 'value2');374 assert.ok(results[2] === 'value3');375 });376 });377 it('Should reject returned promise if listener throw error', () => {378 const emitter = new EventEmitter();379 emitter.subscribe('test', () => {380 return Promise.reject(new Error());381 });382 emitter383 .emitAsync('test')384 .then(() => {})385 .catch((err) => {386 assert.ok(err instanceof Error);387 });388 });389 });390 describe('static emitAsync', () => {391 it('Should emit event and return promise', () => {392 const resultPromise = EventEmitter.emitAsync('test-event--1');393 assert.ok(resultPromise instanceof Promise);394 });395 it('Should resolve returned promise with values that returned from listeners', () => {396 const emitter = new EventEmitter();397 emitter.subscribe('test-event-1', () => {398 return 'result-1';399 });400 emitter.subscribe('test-event-1', () => {401 return true;402 });403 emitter.subscribe('test-event-1', () => {404 return 'test-result-3';405 });406 return EventEmitter407 .emitAsync(emitter, 'test-event-1')408 .then((results) => {409 assert.ok(results[0] === 'result-1');410 assert.ok(results[1] === true);411 assert.ok(results[2] === 'test-result-3');412 });413 });414 it('Promise should be resolved, when resolved all promises returned from listeners', () => {415 const emitter = new EventEmitter();416 emitter.subscribe('test-event-2', () => {417 return new Promise((resolve) => {418 setTimeout(() => {419 resolve('value1');420 }, 500);421 });422 });423 emitter.subscribe('test-event-2', () => {424 return new Promise((resolve) => {425 setTimeout(() => {426 resolve('value2');427 }, 700);428 });429 });430 emitter.subscribe('test-event-2', () => {431 return new Promise((resolve) => {432 setTimeout(() => {433 resolve('value3');434 }, 900);435 });436 });437 return EventEmitter438 .emitAsync(emitter, 'test-event-2')439 .then((results) => {440 assert.ok(results[0] === 'value1');441 assert.ok(results[1] === 'value2');442 assert.ok(results[2] === 'value3');443 });444 });445 it('Should reject returned promise if listener throw error', () => {446 const emitter = new EventEmitter();447 emitter.subscribe('test-event-3', () => {448 return Promise.reject(new Error());449 });450 return EventEmitter451 .emitAsync(emitter, 'test-event-3')452 .then(() => {})453 .catch((err) => {454 assert.ok(err instanceof Error);455 });456 });457 });458 describe('subscribeOnce', () => {459 it('Should call listener only once', () => {460 const emitter = new EventEmitter();461 const event = 'test:event';462 const listener = sinon.stub();463 emitter.subscribeOnce(event, listener);464 emitter.emit(event);465 emitter.emit(event);466 emitter.emit(event);467 emitter.emit(event);468 assert(listener.calledOnce);469 });470 it('Should add only unique listeners', () => {471 const emitter = new EventEmitter();472 const event = 'test:event';473 const listener = sinon.stub();474 emitter.subscribeOnce(event, listener);475 emitter.subscribeOnce(event, listener);476 emitter.subscribeOnce(event, listener);477 emitter.subscribeOnce(event, listener);478 emitter.emit(event);479 emitter.emit(event);480 emitter.emit(event);481 emitter.emit(event);482 assert(listener.calledOnce);483 });484 });485 describe('setMaxListeners', () => {486 it('Should set max allowed listeners count', () => {487 const emitter = new EventEmitter();488 const maxListenersCount = 3;489 emitter.setMaxListeners(maxListenersCount);490 emitter.setMaxListeners('onClose', 5);491 assert(emitter.getMaxListeners() === maxListenersCount);492 assert(emitter.getMaxListeners('onXXX') === maxListenersCount);493 assert(emitter.getMaxListeners('onClose') === 5);494 });495 it('Should set max listeners count for the event', () => {496 const emitter = new EventEmitter();497 const eventName = "MyEventMaxListeners";498 const maxListenersCount = 3;499 emitter.setMaxListeners(eventName, maxListenersCount);500 assert(emitter.getMaxListeners() === EventEmitter.DEFAULT_MAX_LISTENERS);501 assert(emitter.getMaxListeners(eventName) === maxListenersCount);502 assert(EventEmitter.getMaxListeners({}) === EventEmitter.DEFAULT_MAX_LISTENERS);503 assert(EventEmitter.getMaxListeners({}, eventName) === EventEmitter.DEFAULT_MAX_LISTENERS);504 });505 it('Should print warnings if the limit exceeded', () => {506 const obj = {};507 const eventName = "limit-subscribers";508 const eventName2 = "limit-subscribers2";509 const listener1 = sinon.stub();510 const listener2 = sinon.stub();511 const listener3 = sinon.stub();512 const listener4 = sinon.stub();513 EventEmitter.setMaxListeners(obj, eventName, 2);514 assert(EventEmitter.getMaxListeners(obj) === EventEmitter.DEFAULT_MAX_LISTENERS);515 assert(EventEmitter.getMaxListeners(obj, eventName) === 2);516 EventEmitter.subscribe(obj, eventName, listener1);517 EventEmitter.subscribe(obj, eventName, listener2);518 EventEmitter.subscribe(obj, eventName, listener3);519 EventEmitter.subscribe(obj, eventName, listener4);520 EventEmitter.emit(obj, eventName);521 EventEmitter.subscribe(obj, eventName2, listener1);522 EventEmitter.subscribe(obj, eventName2, listener2);523 EventEmitter.subscribe(obj, eventName2, listener3);524 EventEmitter.subscribe(obj, eventName2, listener4);525 EventEmitter.emit(obj, eventName2);526 });527 it('Should sets max listeners for global target', () => {528 const obj = {};529 assert.equal(EventEmitter.getMaxListeners(), 25);530 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS);531 EventEmitter.setMaxListeners(55);532 EventEmitter.setMaxListeners('onMyClick', 77);533 assert.equal(EventEmitter.getMaxListeners(), 55);534 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS);535 assert.equal(EventEmitter.getMaxListeners('onMyClick'), 77);536 assert.equal(EventEmitter.getMaxListeners(obj, 'onMyClick'), EventEmitter.DEFAULT_MAX_LISTENERS);537 EventEmitter.setMaxListeners(obj, 88);538 EventEmitter.setMaxListeners(obj, 'onMyClick', 99);539 assert.equal(EventEmitter.getMaxListeners(), 55);540 assert.equal(EventEmitter.getMaxListeners('onMyClick'), 77);541 assert.equal(EventEmitter.getMaxListeners(obj), 88);542 assert.equal(EventEmitter.getMaxListeners(obj, 'onMyClick'), 99);543 assert.equal(EventEmitter.getMaxListeners(obj, 'onXXX'), 88);544 });545 });546 describe('incrementMaxListeners/decrementMaxListeners', () => {547 it('Should increment/decrement events for the global target', () => {548 const obj = {};549 const eventName = 'onMySpecialEvent';550 const defaultGlobalMaxListeners = EventEmitter.getMaxListeners();551 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners);552 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners);553 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS);554 EventEmitter.incrementMaxListeners();555 EventEmitter.incrementMaxListeners();556 EventEmitter.incrementMaxListeners();557 EventEmitter.setMaxListeners(eventName, defaultGlobalMaxListeners);558 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners + 3);559 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners);560 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS);561 EventEmitter.incrementMaxListeners();562 EventEmitter.incrementMaxListeners();563 EventEmitter.incrementMaxListeners(eventName);564 EventEmitter.incrementMaxListeners(eventName);565 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners + 5);566 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners + 2);567 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS);568 EventEmitter.incrementMaxListeners(3);569 EventEmitter.incrementMaxListeners(eventName);570 EventEmitter.incrementMaxListeners(eventName, 4);571 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners + 8);572 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners + 7);573 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS);574 EventEmitter.incrementMaxListeners(obj, eventName);575 EventEmitter.incrementMaxListeners(obj, eventName);576 EventEmitter.incrementMaxListeners(obj, eventName, 7);577 EventEmitter.incrementMaxListeners(obj);578 EventEmitter.incrementMaxListeners(obj);579 EventEmitter.incrementMaxListeners(obj, 3);580 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners + 8);581 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners + 7);582 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS + 5);583 assert.equal(EventEmitter.getMaxListeners(obj, eventName), EventEmitter.DEFAULT_MAX_LISTENERS + 9);584 EventEmitter.decrementMaxListeners(obj, eventName);585 EventEmitter.decrementMaxListeners(obj, eventName, 7);586 EventEmitter.decrementMaxListeners(obj);587 EventEmitter.decrementMaxListeners(obj, 3);588 assert.equal(EventEmitter.getMaxListeners(obj, eventName), EventEmitter.DEFAULT_MAX_LISTENERS + 1);589 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS + 1);590 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners + 8);591 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners + 7);592 EventEmitter.decrementMaxListeners(3);593 EventEmitter.decrementMaxListeners(eventName);594 EventEmitter.decrementMaxListeners(eventName, 4);595 assert.equal(EventEmitter.getMaxListeners(obj, eventName), EventEmitter.DEFAULT_MAX_LISTENERS + 1);596 assert.equal(EventEmitter.getMaxListeners(obj), EventEmitter.DEFAULT_MAX_LISTENERS + 1);597 assert.equal(EventEmitter.getMaxListeners(), defaultGlobalMaxListeners + 5);598 assert.equal(EventEmitter.getMaxListeners(eventName), defaultGlobalMaxListeners + 2);599 });600 it('Should increment events for an object target', () => {601 const emitter = new EventEmitter();602 const eventName = 'onMyEmitterEvent';603 assert.equal(emitter.getMaxListeners(), EventEmitter.DEFAULT_MAX_LISTENERS);604 assert.equal(emitter.getMaxListeners(eventName), EventEmitter.DEFAULT_MAX_LISTENERS);605 emitter.incrementMaxListeners();606 emitter.incrementMaxListeners();607 emitter.incrementMaxListeners(3);608 emitter.setMaxListeners(eventName, 30);609 assert.equal(emitter.getMaxListeners(), EventEmitter.DEFAULT_MAX_LISTENERS + 5);610 assert.equal(emitter.getMaxListeners(eventName), 30);611 emitter.incrementMaxListeners(eventName);612 emitter.incrementMaxListeners(eventName);613 emitter.incrementMaxListeners(eventName, 3);614 assert.equal(emitter.getMaxListeners(), EventEmitter.DEFAULT_MAX_LISTENERS + 5);615 assert.equal(emitter.getMaxListeners(eventName), 35);616 emitter.decrementMaxListeners();617 emitter.decrementMaxListeners(3);618 emitter.decrementMaxListeners(eventName);619 emitter.decrementMaxListeners(eventName, 2);620 assert.equal(emitter.getMaxListeners(), EventEmitter.DEFAULT_MAX_LISTENERS + 1);621 assert.equal(emitter.getMaxListeners(eventName), 32);622 });623 });624 describe('getMaxListeners', () => {625 it('Should return max listeners count for each event', () => {626 const emitter = new EventEmitter();627 const defaultMaxListenersCount = 10;628 assert(emitter.getMaxListeners() === defaultMaxListenersCount);629 });630 });631 describe('static', () => {632 it('Should implement public static interface', () => {633 assert(typeof EventEmitter.subscribe === 'function');634 assert(typeof EventEmitter.subscribeOnce === 'function');635 assert(typeof EventEmitter.emit === 'function');636 assert(typeof EventEmitter.unsubscribe === 'function');637 assert(typeof EventEmitter.getMaxListeners === 'function');638 assert(typeof EventEmitter.setMaxListeners === 'function');639 assert(typeof EventEmitter.getListeners === 'function');640 });641 it('Should add global event listener', () => {642 const emitter = new EventEmitter();643 const eventName = 'test:event';644 const listener = sinon.stub();645 EventEmitter.subscribe(emitter, eventName, listener);646 emitter.emit(eventName);647 assert(listener.callCount === 1);648 emitter.emit(eventName);649 emitter.emit(eventName);650 assert(listener.callCount === 3);651 });652 });653 describe('Old custom events', () => {654 it('Should implement public static interface', () => {655 assert(typeof BX.addCustomEvent === 'function');656 assert(typeof BX.onCustomEvent === 'function');657 assert(typeof BX.removeCustomEvent === 'function');658 assert(typeof BX.removeAllCustomEvents === 'function');659 });660 it('Should add an event listener', () => {661 const obj = {};662 const eventName = 'old:add-custom-event';663 const listener1 = sinon.stub();664 const listener2 = sinon.stub();665 const listener3 = sinon.stub();666 BX.addCustomEvent(obj, eventName, listener1);667 BX.addCustomEvent(obj, eventName, listener2);668 BX.addCustomEvent(obj, eventName, listener3);669 assert.equal(EventEmitter.getListeners(obj, eventName).size, 3);670 BX.onCustomEvent(obj, eventName);671 assert(listener1.calledOnce);672 assert(listener2.calledOnce);673 assert(listener3.calledOnce);674 });675 it('Should add global listeners', () => {676 const obj = {};677 const eventName = 'old:add-custom-event';678 const listener1 = sinon.stub();679 const listener2 = sinon.stub();680 const listener3 = sinon.stub();681 const listener4 = sinon.stub();682 BX.addCustomEvent(window, eventName, listener1);683 BX.addCustomEvent(eventName, listener2);684 BX.addCustomEvent(EventEmitter.GLOBAL_TARGET, eventName, listener3);685 BX.addCustomEvent(obj, eventName, listener4);686 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 3);687 assert.equal(EventEmitter.getListeners(eventName).size, 3);688 BX.onCustomEvent(window, eventName);689 assert(listener1.callCount === 1);690 assert(listener2.callCount === 1);691 assert(listener3.callCount === 1);692 BX.onCustomEvent(eventName);693 assert(listener1.callCount === 2);694 assert(listener2.callCount === 2);695 assert(listener3.callCount === 2);696 BX.onCustomEvent(obj, eventName);697 assert(listener1.callCount === 3);698 assert(listener2.callCount === 3);699 assert(listener3.callCount === 3);700 assert(listener4.callCount === 1);701 });702 it('Should invoke event listeners', () => {703 const obj = {};704 const eventName = 'test:event';705 const listener = sinon.stub();706 BX.addCustomEvent(obj, eventName, listener);707 BX.onCustomEvent(obj, eventName);708 assert(listener.callCount === 1);709 BX.onCustomEvent(obj, eventName);710 BX.onCustomEvent(obj, eventName);711 assert(listener.callCount === 3);712 });713 it('Should pass arguments', (done) => {714 const obj = {};715 const eventName = 'test:event';716 const listener = function(a, b, c) {717 assert.equal(a, 1);718 assert.equal(b, obj);719 assert.equal(c, "string");720 done();721 };722 BX.addCustomEvent(obj, eventName, listener);723 BX.onCustomEvent(obj, eventName, [1, obj, "string"]);724 });725 it('Should pass array-like arguments', (done) => {726 const obj = {};727 const eventName = 'test:onChanged';728 const listener = function(a, b, c) {729 assert.equal(a, 1);730 assert.equal(b, obj);731 assert.equal(c, "string");732 done();733 };734 function fireEvent()735 {736 BX.onCustomEvent(obj, eventName, arguments);737 }738 BX.addCustomEvent(obj, eventName, listener);739 fireEvent(1, obj, "string");740 });741 it('Should emit params for old handlers', (done) => {742 const emitter = new EventEmitter();743 const eventName = 'onMyPopupClose';744 const listener = (a, b, c) => {745 assert.equal(a, 1);746 assert.equal(b, emitter);747 assert.equal(c, "string");748 done();749 };750 BX.addCustomEvent(emitter, eventName, listener);751 const event = new BaseEvent();752 event.setCompatData([1, emitter, "string"]);753 emitter.emit(eventName, event);754 });755 it('Should emit an event for new handlers', (done) => {756 const emitter = new EventEmitter();757 const eventName = 'onMyPopupClose2';758 const listener = function(event) {759 assert.equal(event.getData(), 2);760 done();761 };762 BX.addCustomEvent(emitter, eventName, listener);763 emitter.emit(eventName, 2);764 });765 it('Should emit an event for new subscribers', (done) => {766 const obj = {};767 const eventName = 'test:event';768 EventEmitter.subscribe(obj, eventName, (event) => {769 const [num, instance, str] = event.getData();770 assert.equal(num, 1);771 assert.equal(instance, obj);772 assert.equal(str, "string");773 done();774 });775 BX.onCustomEvent(obj, eventName, [1, obj, "string"]);776 });777 });778 describe('StopImmediatePropagation', () => {779 it('Should stop invoke the rest listeners', () => {780 const emitter = new EventEmitter();781 const eventName = 'event:stop-propagation';782 const listener1 = sinon.stub();783 const listener2 = (event) => {784 event.stopImmediatePropagation();785 };786 const listener3 = sinon.stub();787 emitter.subscribe(eventName, listener1);788 emitter.subscribe(eventName, listener2);789 emitter.subscribe(eventName, listener3);790 emitter.emit(eventName);791 assert(listener1.callCount === 1);792 assert(listener3.callCount === 0);793 });794 });795 describe('Global Context', () => {796 it('Should add event listeners', () => {797 const eventName = 'event:global-context';798 const listener1 = () => {};799 const listener2 = () => {};800 const listener3 = () => {};801 EventEmitter.subscribe(eventName, listener1);802 EventEmitter.subscribe(eventName, listener2);803 EventEmitter.subscribe(eventName, listener3);804 assert.equal(EventEmitter.getListeners(eventName).size, 3);805 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 3);806 });807 it('Should remove specified event listener', () => {808 const eventName = 'event:global-context-unsubscribe';809 const listener1 = () => {};810 const listener2 = () => {};811 const listener3 = () => {};812 const listener4 = () => {};813 EventEmitter.subscribe(eventName, listener1);814 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener2);815 EventEmitter.subscribe(eventName, listener3);816 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener4);817 assert.equal(EventEmitter.getListeners(eventName).size, 4);818 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 4);819 EventEmitter.unsubscribe(eventName, listener1);820 EventEmitter.unsubscribe(EventEmitter.GLOBAL_TARGET, eventName, listener3);821 assert.equal(EventEmitter.getListeners(eventName).size, 2);822 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 2);823 assert(EventEmitter.getListeners(eventName).has(listener1) === false);824 assert(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).has(listener1) === false);825 assert(EventEmitter.getListeners(eventName).has(listener2) === true);826 assert(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).has(listener2) === true);827 assert(EventEmitter.getListeners(eventName).has(listener3) === false);828 assert(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).has(listener3) === false);829 assert(EventEmitter.getListeners(eventName).has(listener4) === true);830 assert(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).has(listener4) === true);831 });832 it('Should remove all event listeners', () => {833 const eventName = 'event:global-context-unsubscribe-all';834 const eventName2 = 'event:global-context-unsubscribe-all2';835 const listener1 = () => {};836 const listener2 = () => {};837 const listener3 = () => {};838 const listener4 = () => {};839 EventEmitter.subscribe(eventName, listener1);840 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener2);841 EventEmitter.subscribe(eventName, listener3);842 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener4);843 EventEmitter.subscribe(eventName2, listener1);844 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName2, listener2);845 EventEmitter.subscribe(eventName2, listener3);846 assert.equal(EventEmitter.getListeners(eventName).size, 4);847 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 4);848 assert.equal(EventEmitter.getListeners(eventName2).size, 3);849 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName2).size, 3);850 EventEmitter.unsubscribeAll(eventName);851 assert.equal(EventEmitter.getListeners(eventName).size, 0);852 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 0);853 assert.equal(EventEmitter.getListeners(eventName2).size, 3);854 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName2).size, 3);855 EventEmitter.unsubscribeAll(eventName2);856 assert.equal(EventEmitter.getListeners(eventName).size, 0);857 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 0);858 assert.equal(EventEmitter.getListeners(eventName2).size, 0);859 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName2).size, 0);860 });861 it('setMaxListeners', () => {862 EventEmitter.setMaxListeners(111);863 assert.equal(EventEmitter.getMaxListeners(), 111);864 assert.equal(EventEmitter.getMaxListeners(EventEmitter.GLOBAL_TARGET), 111);865 EventEmitter.setMaxListeners(EventEmitter.GLOBAL_TARGET, 222);866 assert.equal(EventEmitter.getMaxListeners(), 222);867 assert.equal(EventEmitter.getMaxListeners(EventEmitter.GLOBAL_TARGET), 222);868 });869 it('subscribeOnce', () => {870 const eventName = 'test:event';871 const listener = () => {};872 const listener2 = () => {};873 const listener3 = () => {};874 const listener4 = () => {};875 EventEmitter.subscribe(eventName, listener);876 EventEmitter.subscribe(eventName, listener);877 EventEmitter.subscribe(eventName, listener);878 EventEmitter.subscribeOnce(eventName, listener);879 EventEmitter.subscribeOnce(eventName, listener);880 EventEmitter.subscribeOnce(eventName, listener);881 EventEmitter.subscribeOnce(eventName, listener2);882 EventEmitter.subscribeOnce(eventName, listener2);883 EventEmitter.subscribeOnce(eventName, listener2);884 EventEmitter.subscribe(eventName, listener2);885 EventEmitter.subscribe(eventName, listener2);886 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener3);887 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener3);888 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener3);889 EventEmitter.subscribeOnce(EventEmitter.GLOBAL_TARGET, eventName, listener3);890 EventEmitter.subscribeOnce(EventEmitter.GLOBAL_TARGET, eventName, listener3);891 EventEmitter.subscribeOnce(EventEmitter.GLOBAL_TARGET, eventName, listener3);892 EventEmitter.subscribeOnce(EventEmitter.GLOBAL_TARGET, eventName, listener4);893 EventEmitter.subscribeOnce(EventEmitter.GLOBAL_TARGET, eventName, listener4);894 EventEmitter.subscribeOnce(EventEmitter.GLOBAL_TARGET, eventName, listener4);895 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener4);896 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener4);897 assert.equal(EventEmitter.getListeners(eventName).size, 4);898 assert.equal(EventEmitter.getListeners(EventEmitter.GLOBAL_TARGET, eventName).size, 4);899 });900 it('emitSync', (done) => {901 const eventName = 'event:async';902 const listener1 = () => {903 return new Promise((resolve) => {904 setTimeout(() => {905 resolve('value1');906 }, 500);907 });908 };909 const listener2 = () => {910 return new Promise((resolve) => {911 setTimeout(() => {912 resolve('value2');913 }, 700);914 });915 };916 const listener3 = () => {917 return new Promise((resolve) => {918 setTimeout(() => {919 resolve('value3');920 }, 900);921 });922 };923 EventEmitter.subscribe(eventName, listener1);924 EventEmitter.subscribe(EventEmitter.GLOBAL_TARGET, eventName, listener2);925 EventEmitter.subscribe(eventName, listener3);926 EventEmitter927 .emitAsync(eventName)928 .then((results) => {929 assert.ok(results[0] === 'value1');930 assert.ok(results[1] === 'value2');931 assert.ok(results[2] === 'value3');932 done();933 });934 });935 });936 describe('Event Namespace', () => {937 it('Should subscribe on a short event name', () => {938 const emitter = new EventEmitter();939 emitter.setEventNamespace('MyCompany.MyModule.MyClass');940 const eventName = 'onOpen';941 const listener1 = sinon.stub();942 const listener2 = sinon.stub().callsFake(function(event) {943 assert.equal(event.getType(), 'MyCompany.MyModule.MyClass:onOpen'.toLowerCase());944 });945 const listener3 = sinon.stub();946 const listener4 = sinon.stub().callsFake(function(event) {947 assert.equal(event.getType(), 'MyCompany.MyModule.MyClass:onOpen'.toLowerCase());948 });949 emitter.subscribe(eventName, listener1);950 EventEmitter.subscribe('MyCompany.MyModule.MyClass:onOpen', listener2);951 EventEmitter.subscribe(emitter, 'onOpen', listener3);952 emitter.subscribe(eventName, listener4);953 emitter.emit(eventName);954 assert.equal(listener1.callCount, 1);955 assert.equal(listener2.callCount, 1);956 assert.equal(listener3.callCount, 1);957 assert.equal(listener4.callCount, 1);958 });959 it('Should subscribe on a full event name if a namespace is empty', () => {960 const emitter = new EventEmitter();961 const eventName = 'MyCompany.MyModule.MyClass:onOpen';962 const listener1 = sinon.stub();963 const listener2 = sinon.stub();964 const listener3 = sinon.stub();965 emitter.subscribe(eventName, listener1);966 EventEmitter.subscribe('MyCompany.MyModule.MyClass:onOpen', listener2);967 EventEmitter.subscribe(emitter, 'MyCompany.MyModule.MyClass:onOpen', listener3);968 emitter.emit(eventName);969 assert(listener1.callCount === 1);970 assert(listener2.callCount === 1);971 assert(listener3.callCount === 1);972 });973 it('Should subscribe on a plain object with a full event name', () => {974 const obj = {};975 const eventName = 'MyCompany.MyModule.MyObject:onOpen';976 const listener1 = sinon.stub().callsFake(function(a, b, c) {977 assert(a === 1);978 assert(b === 'string');979 assert(c === obj);980 assert(this === obj);981 });982 const listener2 = sinon.stub().callsFake(function(event) {983 const { a, b, c } = event.getData();984 assert.equal(a, 2);985 assert.equal(b, 'string2');986 assert(c === obj);987 assert(event.getTarget() === obj);988 assert.equal(event.getType(), 'MyCompany.MyModule.MyObject:onOpen'.toLowerCase());989 });990 const listener3 = sinon.stub().callsFake(function(event) {991 const { a, b, c } = event.getData();992 assert.equal(a, 2);993 assert.equal(b, 'string2');994 assert(c === obj);995 assert(event.getTarget() === obj);996 });997 BX.addCustomEvent(obj, eventName, listener1);998 EventEmitter.subscribe('MyCompany.MyModule.MyObject:onOpen', listener2);999 EventEmitter.subscribe(obj, 'MyCompany.MyModule.MyObject:onOpen', listener3);1000 EventEmitter.emit(1001 obj,1002 'MyCompany.MyModule.MyObject:onOpen',1003 new BaseEvent({ compatData: [1, "string", obj], data: { a: 2, b: 'string2', c: obj } })1004 );1005 assert(listener1.callCount === 1);1006 assert(listener2.callCount === 1);1007 assert(listener3.callCount === 1);1008 });1009 });1010 describe('Aliases', () => {1011 EventEmitter.registerAliases({1012 onPopupClose: { namespace: 'MyCompany.MyModule.MyPopup', eventName: 'onClose' },1013 onPopupOpen: { namespace: 'MyCompany.MyModule.MyPopup', eventName: 'onOpen' },1014 onPopupHide: { namespace: 'MyCompany.MyModule.MyPopup', eventName: 'onHide' },1015 onPopupDestroy: { namespace: 'MyCompany.MyModule.MyPopup', eventName: 'onDestroy' },1016 });1017 class MyPopup extends EventEmitter1018 {1019 constructor()1020 {1021 super();1022 this.setEventNamespace('MyCompany.MyModule.MyPopup');1023 }1024 show()1025 {1026 this.emit('onOpen');1027 }1028 close()1029 {1030 this.emit('onClose');1031 }1032 destroy()1033 {1034 this.emit('onDestroy');1035 }1036 }1037 class MySlider extends EventEmitter1038 {1039 constructor()1040 {1041 super();1042 this.setEventNamespace('MyCompany.MyModule.MySlider');1043 }1044 show()1045 {1046 this.emit('onOpen');1047 }1048 close()1049 {1050 this.emit('onClose');1051 }1052 }1053 it('Should subscribe and unsubscribe old event names', () => {1054 const onClose1 = sinon.stub();1055 const onClose2 = sinon.stub();1056 const onClose3Once = sinon.stub();1057 const onClose4 = sinon.stub();1058 const onClose5Once = sinon.stub();1059 const onDestroy = sinon.stub();1060 const onDestroyGlobal = sinon.stub();1061 const onOpen1 = sinon.stub();1062 const onOpen2 = sinon.stub();1063 const onOpen3 = sinon.stub();1064 const onHide1Once = sinon.stub();1065 const onHide2 = sinon.stub();1066 const onHide3 = sinon.stub();1067 const onHide4 = sinon.stub();1068 const onHide5 = sinon.stub();1069 BX.addCustomEvent('onPopupClose', onClose1);1070 EventEmitter.subscribe('onPopupClose', onClose2);1071 EventEmitter.subscribeOnce('onPopupClose', onClose3Once);1072 BX.addCustomEvent('onPopupOpen', onOpen1);1073 EventEmitter.subscribe('MyCompany.MyModule.MyPopup:onOpen', onOpen2);1074 EventEmitter.subscribeOnce('MyCompany.MyModule.MyPopup:onHide', onHide1Once);1075 BX.addCustomEvent('onPopupHide', onHide2);1076 assert.equal(EventEmitter.getListeners('onPopupClose').size, 3);1077 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 2);1078 assert.equal(EventEmitter.getListeners('onPopupHide').size, 2);1079 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 3);1080 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 2);1081 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 2);1082 const popup = new MyPopup();1083 popup.subscribe('onClose', onClose4);1084 popup.subscribeOnce('onClose', onClose5Once);1085 popup.subscribe('onOpen', onOpen3);1086 popup.subscribe('onHide', onHide3);1087 popup.subscribe('onHide', onHide4);1088 popup.subscribe('onHide', onHide5);1089 BX.addCustomEvent('onPopupDestroy', onDestroyGlobal);1090 BX.addCustomEvent(popup, 'onPopupDestroy', onDestroy);1091 assert.equal(popup.getListeners('onClose').size, 2);1092 assert.equal(popup.getListeners('onOpen').size, 1);1093 assert.equal(popup.getListeners('onHide').size, 3);1094 assert.equal(popup.getListeners('onDestroy').size, 1);1095 assert.equal(EventEmitter.getListeners('onPopupClose').size, 3);1096 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 2);1097 assert.equal(EventEmitter.getListeners('onPopupDestroy').size, 1);1098 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 3);1099 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 2);1100 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 2);1101 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onDestroy').size, 1);1102 popup.show();1103 popup.close();1104 assert.equal(onClose1.callCount, 1);1105 assert.equal(onClose2.callCount, 1);1106 assert.equal(onClose3Once.callCount, 1);1107 assert.equal(onClose4.callCount, 1);1108 assert.equal(onClose5Once.callCount, 1);1109 assert.equal(onOpen1.callCount, 1);1110 assert.equal(onOpen2.callCount, 1);1111 assert.equal(onOpen3.callCount, 1);1112 assert.equal(onHide1Once.callCount, 0);1113 assert.equal(onHide2.callCount, 0);1114 assert.equal(onHide3.callCount, 0);1115 assert.equal(onDestroy.callCount, 0);1116 assert.equal(onDestroyGlobal.callCount, 0);1117 popup.show();1118 popup.close();1119 popup.destroy();1120 assert.equal(onClose1.callCount, 2);1121 assert.equal(onClose2.callCount, 2);1122 assert.equal(onClose3Once.callCount, 1);1123 assert.equal(onClose4.callCount, 2);1124 assert.equal(onClose5Once.callCount, 1);1125 assert.equal(onOpen1.callCount, 2);1126 assert.equal(onOpen2.callCount, 2);1127 assert.equal(onOpen3.callCount, 2);1128 assert.equal(onHide1Once.callCount, 0);1129 assert.equal(onHide2.callCount, 0);1130 assert.equal(onHide3.callCount, 0);1131 assert.equal(onDestroy.callCount, 1);1132 assert.equal(onDestroyGlobal.callCount, 1);1133 BX.onCustomEvent('onPopupClose');1134 BX.onCustomEvent(popup, 'onPopupClose');1135 BX.onCustomEvent('MyCompany.MyModule.MyPopup:onClose');1136 BX.onCustomEvent(popup, 'onPopupClose');1137 BX.onCustomEvent('MyCompany.MyModule.MyPopup:onOpen');1138 BX.onCustomEvent(popup, 'onPopupOpen');1139 BX.onCustomEvent('onPopupDestroy');1140 BX.onCustomEvent(popup, 'onPopupDestroy');1141 BX.onCustomEvent('MyCompany.MyModule.MyPopup:onDestroy');1142 assert.equal(onClose1.callCount, 6);1143 assert.equal(onClose2.callCount, 6);1144 assert.equal(onClose3Once.callCount, 1);1145 assert.equal(onClose4.callCount, 4);1146 assert.equal(onClose5Once.callCount, 1);1147 assert.equal(onOpen1.callCount, 4);1148 assert.equal(onOpen2.callCount, 4);1149 assert.equal(onOpen3.callCount, 3);1150 assert.equal(onHide1Once.callCount, 0);1151 assert.equal(onHide2.callCount, 0);1152 assert.equal(onHide3.callCount, 0);1153 assert.equal(onDestroy.callCount, 2);1154 assert.equal(onDestroyGlobal.callCount, 4);1155 EventEmitter.emit('onPopupClose');1156 EventEmitter.emit(popup, 'onClose');1157 EventEmitter.emit('MyCompany.MyModule.MyPopup:onOpen');1158 EventEmitter.emit('onPopupDestroy');1159 EventEmitter.emit(popup, 'onDestroy');1160 EventEmitter.emit('MyCompany.MyModule.MyPopup:onDestroy');1161 assert.equal(onClose1.callCount, 8);1162 assert.equal(onClose2.callCount, 8);1163 assert.equal(onClose3Once.callCount, 1);1164 assert.equal(onClose4.callCount, 5);1165 assert.equal(onClose5Once.callCount, 1);1166 assert.equal(onOpen1.callCount, 5);1167 assert.equal(onOpen2.callCount, 5);1168 assert.equal(onOpen3.callCount, 3);1169 assert.equal(onHide1Once.callCount, 0);1170 assert.equal(onHide2.callCount, 0);1171 assert.equal(onHide3.callCount, 0);1172 assert.equal(onDestroy.callCount, 3);1173 assert.equal(onDestroyGlobal.callCount, 7);1174 assert.equal(popup.getListeners('onClose').size, 1);1175 assert.equal(popup.getListeners('onDestroy').size, 1);1176 assert.equal(EventEmitter.getListeners('onPopupClose').size, 2);1177 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 2);1178 BX.removeCustomEvent('onPopupClose', onClose1);1179 BX.removeCustomEvent('onPopupOpen', onOpen1);1180 BX.removeCustomEvent('onPopupHide', onHide1Once);1181 BX.removeCustomEvent(popup, 'onPopupDestroy', onDestroy);1182 assert.equal(popup.getListeners('onClose').size, 1);1183 assert.equal(popup.getListeners('onOpen').size, 1);1184 assert.equal(popup.getListeners('onHide').size, 3);1185 assert.equal(EventEmitter.getListeners('onPopupClose').size, 1);1186 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 1);1187 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 1);1188 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 1);1189 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 1);1190 assert.equal(popup.getListeners('onDestroy').size, 0);1191 assert.equal(EventEmitter.getListeners('onPopupDestroy').size, 1);1192 BX.removeCustomEvent('onPopupDestroy', onDestroyGlobal);1193 assert.equal(popup.getListeners('onDestroy').size, 0);1194 assert.equal(EventEmitter.getListeners('onPopupDestroy').size, 0);1195 EventEmitter.unsubscribe('onPopupClose', onClose2);1196 EventEmitter.unsubscribe('MyCompany.MyModule.MyPopup:onClose', onClose3Once);1197 EventEmitter.unsubscribe('MyCompany.MyModule.MyPopup:onOpen', onOpen2);1198 EventEmitter.unsubscribe('MyCompany.MyModule.MyPopup:onHide', onHide2);1199 assert.equal(popup.getListeners('onClose').size, 1);1200 assert.equal(popup.getListeners('onOpen').size, 1);1201 assert.equal(popup.getListeners('onHide').size, 3);1202 assert.equal(EventEmitter.getListeners('onPopupClose').size, 0);1203 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 0);1204 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 0);1205 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 0);1206 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 0);1207 popup.unsubscribe('onClose', onClose4);1208 popup.unsubscribe('onClose', onClose5Once);1209 popup.unsubscribe('onOpen', onOpen3);1210 assert.equal(popup.getListeners('onClose').size, 0);1211 assert.equal(popup.getListeners('onOpen').size, 0);1212 assert.equal(popup.getListeners('onHide').size, 3);1213 popup.unsubscribeAll('onHide');1214 assert.equal(popup.getListeners('onHide').size, 0);1215 });1216 it('Should unsubscribe all event names', () => {1217 const listener1 = sinon.stub();1218 const listener2 = sinon.stub();1219 const listener3 = sinon.stub();1220 const listener4 = sinon.stub();1221 const listener5 = sinon.stub();1222 const listener6 = sinon.stub();1223 const listener7 = sinon.stub();1224 const listener8 = sinon.stub();1225 const listenerOnce1 = sinon.stub();1226 const listenerOnce2 = sinon.stub();1227 const listenerOnce3 = sinon.stub();1228 BX.addCustomEvent('onPopupClose', listener1);1229 BX.addCustomEvent('onPopupOpen', listener2);1230 BX.addCustomEvent('onPopupHide', listener7);1231 EventEmitter.subscribe('onPopupClose', listener3);1232 EventEmitter.subscribeOnce('onPopupClose', listenerOnce1);1233 EventEmitter.subscribe('MyCompany.MyModule.MyPopup:onOpen', listener4);1234 EventEmitter.subscribeOnce('MyCompany.MyModule.MyPopup:onHide', listenerOnce3);1235 const popup = new MyPopup();1236 popup.subscribe('onClose', listener5);1237 popup.subscribeOnce('onClose', listenerOnce2);1238 popup.subscribe('onOpen', listener6);1239 popup.subscribe('onHide', listener8);1240 assert.equal(EventEmitter.getListeners('onPopupClose').size, 3);1241 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 3);1242 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 2);1243 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 2);1244 assert.equal(EventEmitter.getListeners('onPopupHide').size, 2);1245 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 2);1246 assert.equal(popup.getListeners('onClose').size, 2);1247 assert.equal(popup.getListeners('onOpen').size, 1);1248 assert.equal(popup.getListeners('onHide').size, 1);1249 popup.unsubscribeAll('onClose');1250 assert.equal(popup.getListeners('onClose').size, 0);1251 assert.equal(popup.getListeners('onOpen').size, 1);1252 assert.equal(popup.getListeners('onHide').size, 1);1253 assert.equal(EventEmitter.getListeners('onPopupClose').size, 3);1254 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 3);1255 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 2);1256 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 2);1257 assert.equal(EventEmitter.getListeners('onPopupHide').size, 2);1258 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 2);1259 EventEmitter.unsubscribeAll('MyCompany.MyModule.MyPopup:onClose');1260 assert.equal(popup.getListeners('onClose').size, 0);1261 assert.equal(popup.getListeners('onOpen').size, 1);1262 assert.equal(popup.getListeners('onHide').size, 1);1263 assert.equal(EventEmitter.getListeners('onPopupClose').size, 0);1264 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 0);1265 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 2);1266 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 2);1267 assert.equal(EventEmitter.getListeners('onPopupHide').size, 2);1268 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 2);1269 EventEmitter.unsubscribeAll('onPopupHide');1270 assert.equal(popup.getListeners('onClose').size, 0);1271 assert.equal(popup.getListeners('onOpen').size, 1);1272 assert.equal(popup.getListeners('onHide').size, 1);1273 assert.equal(EventEmitter.getListeners('onPopupClose').size, 0);1274 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 0);1275 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 2);1276 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 2);1277 assert.equal(EventEmitter.getListeners('onPopupHide').size, 0);1278 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 0);1279 popup.unsubscribeAll();1280 EventEmitter.unsubscribeAll('onPopupOpen');1281 assert.equal(popup.getListeners('onClose').size, 0);1282 assert.equal(popup.getListeners('onOpen').size, 0);1283 assert.equal(popup.getListeners('onHide').size, 0);1284 assert.equal(EventEmitter.getListeners('onPopupClose').size, 0);1285 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onClose').size, 0);1286 assert.equal(EventEmitter.getListeners('onPopupOpen').size, 0);1287 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onOpen').size, 0);1288 assert.equal(EventEmitter.getListeners('onPopupHide').size, 0);1289 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MyPopup:onHide').size, 0);1290 });1291 it('Should rebuild event map after an alias registration', () => {1292 const listener1 = sinon.stub();1293 const listener2 = sinon.stub();1294 const listener3 = sinon.stub();1295 const listener4 = sinon.stub();1296 const listener5 = sinon.stub();1297 const listener6 = sinon.stub();1298 const listener7 = sinon.stub();1299 const listener8 = sinon.stub();1300 const listener9 = sinon.stub();1301 const listener10 = sinon.stub();1302 const listener11 = sinon.stub();1303 const listener12 = sinon.stub();1304 BX.addCustomEvent('onSliderClose', listener1);1305 BX.addCustomEvent('onSliderOpen', listener2);1306 BX.addCustomEvent('onSliderHide', listener3);1307 EventEmitter.setMaxListeners('onSliderOpen', 33);1308 EventEmitter.setMaxListeners('MyCompany.MyModule.MySlider:onOpen', 66);1309 EventEmitter.setMaxListeners('onSliderClose', 99);1310 EventEmitter.setMaxListeners('MyCompany.MyModule.MySlider:onHide', 10);1311 EventEmitter.subscribe('onSliderClose', listener4);1312 EventEmitter.subscribeOnce('onSliderClose', listener5);1313 EventEmitter.subscribe('MyCompany.MyModule.MySlider:onClose', listener11);1314 EventEmitter.subscribe('MyCompany.MyModule.MySlider:onClose', listener12);1315 EventEmitter.subscribe('MyCompany.MyModule.MySlider:onOpen', listener6);1316 EventEmitter.subscribe('MyCompany.MyModule.MySlider:onOpen', listener11);1317 assert.equal(EventEmitter.getListeners('onSliderClose').size, 3);1318 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MySlider:onClose').size, 2);1319 assert.equal(EventEmitter.getListeners('onSliderOpen').size, 1);1320 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MySlider:onOpen').size, 2);1321 assert.equal(EventEmitter.getListeners('onSliderHide').size, 1);1322 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MySlider:onHide').size, 0);1323 const globalTargetMaxListeners = EventEmitter.getMaxListeners();1324 assert.equal(EventEmitter.getMaxListeners('onSliderOpen'), 33);1325 assert.equal(EventEmitter.getMaxListeners('MyCompany.MyModule.MySlider:onOpen'), 66);1326 assert.equal(EventEmitter.getMaxListeners('onSliderClose'), 99);1327 assert.equal(EventEmitter.getMaxListeners('MyCompany.MyModule.MySlider:onClose'), globalTargetMaxListeners);1328 assert.equal(EventEmitter.getMaxListeners('MyCompany.MyModule.MySlider:onHide'), 10);1329 assert.equal(EventEmitter.getMaxListeners('onSliderHide'), globalTargetMaxListeners);1330 EventEmitter.registerAliases({1331 onSliderClose: { namespace: 'MyCompany.MyModule.MySlider', eventName: 'onClose' },1332 onSliderOpen: { namespace: 'MyCompany.MyModule.MySlider', eventName: 'onOpen' },1333 onSliderHide: { namespace: 'MyCompany.MyModule.MySlider', eventName: 'onHide' },1334 });1335 EventEmitter.subscribeOnce('MyCompany.MyModule.MySlider:onHide', listener7);1336 assert.equal(EventEmitter.getListeners('onSliderClose').size, 5);1337 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MySlider:onClose').size, 5);1338 assert.equal(EventEmitter.getListeners('onSliderOpen').size, 3);1339 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MySlider:onOpen').size, 3);1340 assert.equal(EventEmitter.getListeners('onSliderHide').size, 2);1341 assert.equal(EventEmitter.getListeners('MyCompany.MyModule.MySlider:onHide').size, 2);1342 assert.equal(EventEmitter.getMaxListeners('onSliderOpen'), 66);1343 assert.equal(EventEmitter.getMaxListeners('MyCompany.MyModule.MySlider:onOpen'), 66);1344 assert.equal(EventEmitter.getMaxListeners('onSliderClose'), 99);1345 assert.equal(EventEmitter.getMaxListeners('MyCompany.MyModule.MySlider:onHide'), 10);1346 const slider = new MySlider();1347 slider.subscribe('onClose', listener8);1348 slider.subscribe('onClose', listener12);1349 slider.subscribeOnce('onClose', listener9);1350 slider.subscribe('onOpen', listener10);1351 slider.show();1352 slider.close();1353 slider.show();1354 slider.close();1355 slider.emit('onHide');1356 slider.emit('onHide');1357 assert.equal(listener1.callCount, 2);1358 assert.equal(listener2.callCount, 2);1359 assert.equal(listener3.callCount, 2);1360 assert.equal(listener4.callCount, 2);1361 assert.equal(listener5.callCount, 1);1362 assert.equal(listener6.callCount, 2);1363 assert.equal(listener7.callCount, 1);1364 assert.equal(listener8.callCount, 2);1365 assert.equal(listener9.callCount, 1);1366 assert.equal(listener10.callCount, 2);1367 assert.equal(listener11.callCount, 4);1368 assert.equal(listener12.callCount, 4);1369 });1370 class MyNewClass extends EventEmitter1371 {1372 constructor(options)1373 {1374 super();1375 this.setEventNamespace('MyModule.MyNewClass');1376 this.subscribeFromOptions(options.events);1377 }1378 }1379 const aliases = {1380 onOldPopupClose: { namespace: 'MyModule.MyNewPopup', eventName: 'onClose' },1381 onOldPopupOpen: { namespace: 'MyModule.MyNewPopup', eventName: 'onOpen' },1382 };1383 EventEmitter.registerAliases(aliases);1384 class MyNewPopup extends EventEmitter1385 {1386 constructor(options)1387 {1388 super();1389 this.setEventNamespace('MyModule.MyNewPopup');1390 this.subscribeFromOptions(options.events, aliases);1391 }1392 }1393 class MyOldSlider extends EventEmitter1394 {1395 constructor(options)1396 {1397 super();1398 this.setEventNamespace('MyModule.MyOldSlider');1399 this.subscribeFromOptions(options.events, null, true);1400 }1401 }1402 it('Should subscribe from options', () => {1403 const listener1 = sinon.stub();1404 const listener2 = sinon.stub();1405 const listener3 = sinon.stub();1406 const listener4 = sinon.stub();1407 const listener5 = sinon.stub().callsFake((a, b, c) => {1408 assert.equal(a, 1);1409 assert.equal(b, 2);1410 assert.equal(c, 3);1411 });1412 const listener6 = sinon.stub().callsFake((a, b, c) => {1413 assert.equal(a, 1);1414 assert.equal(b, 2);1415 assert.equal(c, 3);1416 });1417 const listener7 = sinon.stub().callsFake((event) => {1418 assert.equal(event.getData(), 100);1419 });1420 const listener8 = sinon.stub().callsFake((event) => {1421 assert.equal(event.getData(), 100);1422 });1423 const newClass = new MyNewClass({1424 events: {1425 onOpen: listener1,1426 onClose: listener2,1427 }1428 });1429 assert.equal(newClass.getListeners('onOpen').size, 1);1430 assert.equal(newClass.getListeners('onClose').size, 1);1431 newClass.emit('onClose');1432 newClass.emit('onClose');1433 newClass.emit('onOpen');1434 assert.equal(listener1.callCount, 1);1435 assert.equal(listener2.callCount, 2);1436 const oldSlider = new MyOldSlider({1437 events: {1438 onOpen: listener3,1439 onClose: listener4,1440 }1441 });1442 assert.equal(oldSlider.getListeners('onOpen').size, 1);1443 assert.equal(oldSlider.getListeners('onClose').size, 1);1444 oldSlider.emit('onClose');1445 oldSlider.emit('onOpen');1446 assert.equal(listener3.callCount, 1);1447 assert.equal(listener4.callCount, 1);1448 const newPopup = new MyNewPopup({1449 events: {1450 onOldPopupClose: listener5,1451 onOldPopupOpen: listener6,1452 onClose: listener7,1453 onOpen: listener8,1454 }1455 });1456 assert.equal(newPopup.getListeners('onOpen').size, 2);1457 assert.equal(newPopup.getListeners('onClose').size, 2);1458 const event = new BaseEvent({ compatData: [1,2,3], data: 100 });1459 newPopup.emit('onClose', event);1460 newPopup.emit('onClose', event);1461 newPopup.emit('onClose', event);1462 newPopup.emit('onOpen', event);1463 newPopup.emit('onOpen', event);1464 assert.equal(listener5.callCount, 3);1465 assert.equal(listener6.callCount, 2);1466 assert.equal(listener7.callCount, 3);1467 assert.equal(listener8.callCount, 2);1468 });1469 });1470 describe('Event errors', () => {1471 it('Should add errors', () => {1472 const listener1 = (event) => {1473 event.setError(new BaseError('There is an error 1.', 'my-error-1'));1474 };1475 const listener2 = (event) => {1476 event.setError(new BaseError('There is an error 2.', 'my-error-2', { code: 123 }));1477 };1478 const listener3 = (event) => {1479 event.preventDefault();1480 };1481 const emitter = new EventEmitter();1482 emitter.subscribe('onClose', listener1);1483 emitter.subscribe('onClose', listener2);1484 emitter.subscribe('onOpen', listener2);1485 emitter.subscribe('onHide', listener3);1486 const event1 = new BaseEvent();1487 const event2 = new BaseEvent();1488 const event3 = new BaseEvent();1489 emitter.emit('onClose', event1);1490 emitter.emit('onOpen', event2);1491 emitter.emit('onHide', event3);1492 assert.equal(event1.getErrors().length, 2);1493 assert.equal(event2.getErrors().length, 1);1494 assert.equal(event3.getErrors().length, 0);1495 assert.equal(event1.getErrors()[0].getMessage(), 'There is an error 1.');1496 assert.equal(event1.getErrors()[0].getCode(), 'my-error-1');1497 assert.equal(event1.getErrors()[0].getCustomData(), null);1498 assert.equal(event1.getErrors()[1].getMessage(), 'There is an error 2.');1499 assert.equal(event1.getErrors()[1].getCode(), 'my-error-2');1500 assert.equal(event1.getErrors()[1].getCustomData().code, 123);1501 assert.equal(event2.getErrors()[0].getMessage(), 'There is an error 2.');1502 assert.equal(event2.getErrors()[0].getCode(), 'my-error-2');1503 assert.equal(event2.getErrors()[0].getCustomData().code, 123);1504 });1505 });1506 describe('Emitter Composition', () => {1507 class CatalogBaseComponent1508 {1509 constructor()1510 {1511 this.a = 123;1512 this.emitter = new EventEmitter(this, 'BX.Catalog.Component');1513 }1514 getEmitter()1515 {1516 return this.emitter;1517 }1518 show()1519 {1520 this.emitter.emit('onOpen');1521 }1522 close()1523 {1524 this.emitter.emit('onClose', { b: 234 });1525 }1526 hide()1527 {1528 this.emitter.emit('onHide', { c: "12345" });1529 }1530 }1531 it('Should set a namespace via constructor', () => {1532 const component = new CatalogBaseComponent();1533 assert.equal(component.getEmitter().getEventNamespace(), 'BX.Catalog.Component');1534 });1535 it('Should emit an event with an entity target', () => {1536 const component = new CatalogBaseComponent();1537 const listener1 = sinon.stub().callsFake(function(event: typeof(BaseEvent)) {1538 assert.equal(event.getTarget(), component);1539 assert.equal(event.getTarget().a, 123);1540 assert.equal(event.getType(), 'BX.Catalog.Component:onOpen'.toLowerCase());1541 });1542 const listener2 = sinon.stub().callsFake(function(event: typeof(BaseEvent)) {1543 const openEventName = 'BX.Catalog.Component:onOpen'.toLowerCase();1544 const closeEventName = 'BX.Catalog.Component:onClose'.toLowerCase();1545 assert.equal(event.getTarget(), component);1546 assert.equal(event.getTarget().a, 123);1547 assert([openEventName, closeEventName].includes(event.getType()));1548 });1549 const listener3 = sinon.stub().callsFake(function(event: typeof(BaseEvent)) {1550 assert.equal(event.getTarget(), component);1551 assert.equal(event.getType(), 'BX.Catalog.Component:onOpen'.toLowerCase());1552 });1553 const listener4 = sinon.stub().callsFake(function(event: typeof(BaseEvent)) {1554 assert.equal(event.getTarget(), component);1555 assert.equal(event.getData().c, "12345");1556 assert.equal(event.getType(), 'BX.Catalog.Component:onHide'.toLowerCase());1557 });1558 const listener5 = sinon.stub().callsFake(function(event: typeof(BaseEvent)) {1559 assert.equal(event.getTarget(), component);1560 assert.equal(event.getType(), 'BX.Catalog.Component:onClose'.toLowerCase());1561 });1562 component.getEmitter().subscribe('onOpen', listener1);1563 component.getEmitter().subscribe('onOpen', listener2);1564 component.getEmitter().subscribe('onClose', listener2);1565 EventEmitter.subscribe('BX.Catalog.Component:onOpen', listener3);1566 EventEmitter.subscribe('BX.Catalog.Component:onHide', listener4);1567 EventEmitter.subscribe(component.getEmitter(), 'onClose', listener5);1568 component.show();1569 component.close();1570 component.hide();1571 component.hide();1572 assert.equal(listener1.callCount, 1);1573 assert.equal(listener2.callCount, 2);1574 assert.equal(listener3.callCount, 1);1575 assert.equal(listener4.callCount, 2);1576 assert.equal(listener5.callCount, 1);1577 });1578 });1579 describe('Make an observable object', () => {1580 class Parent1581 {1582 constructor()1583 {1584 this.parentProperty = 1;1585 }1586 doMethod()1587 {1588 return "123";1589 }1590 }1591 /**1592 * @mixes EventEmitter1593 */1594 class Child extends Parent1595 {1596 constructor()1597 {1598 super();1599 EventEmitter.makeObservable(this, 'Module.Child');1600 this.childProperty = 2;1601 }1602 show()1603 {1604 this.emit('onShow');1605 }1606 close()1607 {1608 this.emit('onClose');1609 }1610 hide()1611 {1612 this.emit('onHide');1613 }1614 doMethod()1615 {1616 return super.doMethod() + "456";1617 }1618 }1619 it('Should implement public interface', () => {1620 const child = new Child();1621 assert(typeof child.subscribe === 'function');1622 assert(typeof child.subscribeOnce === 'function');1623 assert(typeof child.emit === 'function');1624 assert(typeof child.unsubscribe === 'function');1625 assert(typeof child.getMaxListeners === 'function');1626 assert(typeof child.setMaxListeners === 'function');1627 assert(typeof child.getListeners === 'function');1628 assert(typeof child.incrementMaxListeners === 'function');1629 assert(typeof child.decrementMaxListeners === 'function');1630 });1631 it('Should implement public interface (plain object)', () => {1632 const obj = { a: 23, b: "eeee"};1633 EventEmitter.makeObservable(obj, 'Module.MyObject');1634 assert(typeof obj.subscribe === 'function');1635 assert(typeof obj.subscribeOnce === 'function');1636 assert(typeof obj.emit === 'function');1637 assert(typeof obj.unsubscribe === 'function');1638 assert(typeof obj.getMaxListeners === 'function');1639 assert(typeof obj.setMaxListeners === 'function');1640 assert(typeof obj.getListeners === 'function');1641 assert(typeof obj.incrementMaxListeners === 'function');1642 assert(typeof obj.decrementMaxListeners === 'function');1643 });1644 it('Should emit and subscribe', () => {1645 const listener1 = sinon.stub();1646 const listener2 = sinon.stub();1647 const listener3 = sinon.stub();1648 const listener4 = sinon.stub();1649 const child = new Child();1650 child.subscribe('onClose', listener1);1651 child.subscribe('onShow', listener2);1652 EventEmitter.subscribe('Module.Child:onHide', listener3);1653 EventEmitter.subscribe(child, 'onHide', listener4);1654 child.show();1655 child.close();1656 child.close();1657 child.hide();1658 assert.equal(listener1.callCount, 2);1659 assert.equal(listener2.callCount, 1);1660 assert.equal(listener3.callCount, 1);1661 assert.equal(listener4.callCount, 1);1662 assert.equal(child.childProperty, 2);1663 assert.equal(child.parentProperty, 1);1664 assert.equal(child.doMethod(), "123456");1665 });1666 it('Should make a plain object observable', () => {1667 /**1668 * @mixes EventEmitter1669 */1670 const obj = {1671 a: 5,1672 getValue: function() {1673 return this.a;1674 },1675 show: function() {1676 this.emit('onShow');1677 },1678 close: function() {1679 this.emit('onClose');1680 },1681 hide: function() {1682 this.emit('onHide');1683 }1684 };1685 EventEmitter.makeObservable(obj, 'Module.MyObject');1686 const listener1 = sinon.stub();1687 const listener2 = sinon.stub();1688 const listener3 = sinon.stub();1689 const listener4 = sinon.stub();1690 obj.subscribe('onClose', listener1);1691 obj.subscribe('onShow', listener2);1692 EventEmitter.subscribe('Module.MyObject:onHide', listener3);1693 EventEmitter.subscribe(obj, 'onHide', listener4);1694 obj.show();1695 obj.close();1696 obj.close();1697 obj.hide();1698 assert.equal(listener1.callCount, 2);1699 assert.equal(listener2.callCount, 1);1700 assert.equal(listener3.callCount, 1);1701 assert.equal(listener4.callCount, 1);1702 assert.equal(obj.getValue(), 5);1703 });1704 });...

Full Screen

Full Screen

ParticleTest.js

Source:ParticleTest.js Github

copy

Full Screen

1/****************************************************************************2 Copyright (c) 2008-2010 Ricardo Quesada3 Copyright (c) 2011-2012 cocos2d-x.org4 Copyright (c) 2013-2017 Chukong Technologies Inc.5 http://www.cocos2d-x.org6 Permission is hereby granted, free of charge, to any person obtaining a copy7 of this software and associated documentation files (the "Software"), to deal8 in the Software without restriction, including without limitation the rights9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10 copies of the Software, and to permit persons to whom the Software is11 furnished to do so, subject to the following conditions:12 The above copyright notice and this permission notice shall be included in13 all copies or substantial portions of the Software.14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN20 THE SOFTWARE.21 ****************************************************************************/22var TAG_LABEL_ATLAS = 1;23var particleSceneIdx = -1;24var ParticleTestScene = TestScene.extend({25 runThisTest:function (num) {26 particleSceneIdx = (num || num == 0) ? (num - 1) : -1;27 this.addChild(nextParticleAction());28 director.runScene(this);29 }30});31var particleSceneArr = [32 function () {33 return new DemoFlower();34 },35 function () {36 return new DemoGalaxy();37 },38 function () {39 return new DemoFirework();40 },41 function () {42 return new DemoSpiral();43 },44 function () {45 return new DemoSun();46 },47 function () {48 return new DemoMeteor();49 },50 function () {51 return new DemoFire();52 },53 function () {54 return new DemoSmoke();55 },56 function () {57 return new DemoExplosion();58 },59 function () {60 return new DemoSnow();61 },62 function () {63 return new DemoRain();64 },65 function () {66 return new DemoBigFlower();67 },68 function () {69 return new DemoRotFlower();70 },71 function () {72 return new DemoModernArt();73 },74 function () {75 return new DemoRing();76 },77 function () {78 return new DemoParticleFromFile("BoilingFoam");79 },80 function () {81 return new DemoParticleFromFile("BurstPipe");82 },83 function () {84 return new DemoParticleFromFile("Comet");85 },86 function () {87 return new DemoParticleFromFile("debian");88 },89 function () {90 return new DemoParticleFromFile("ExplodingRing");91 },92 function () {93 return new DemoParticleFromFile("LavaFlow");94 },95 function(){96 return new DemoParticleFromFile("SpinningPeas");97 },98 function () {99 return new DemoParticleFromFile("SpookyPeas");100 },101 function () {102 return new DemoParticleFromFile("Upsidedown");103 },104 function () {105 return new DemoParticleFromFile("Flower");106 },107 function () {108 return new DemoParticleFromFile("Spiral");109 },110 function () {111 return new DemoParticleFromFile("Galaxy");112 },113 function () {114 return new RadiusMode1();115 },116 function () {117 return new RadiusMode2();118 },119 function () {120 return new Issue704();121 },122 function () {123 return new Issue870();124 },125 function () {126 return new DemoParticleFromFile("Phoenix");127 },128 function() {129 return new ParticleResizeTest();130 },131 function() {132 return new DemoPause();133 }134];135if( 'opengl' in cc.sys.capabilities && cc._renderType === cc.game.RENDER_TYPE_WEBGL){136 particleSceneArr.push( function () {137 return new ParallaxParticle();138 });139 particleSceneArr.push(function () {140 return new ParticleBatchTest();141 });142}143var nextParticleAction = function () {144 particleSceneIdx++;145 particleSceneIdx = particleSceneIdx % particleSceneArr.length;146 return particleSceneArr[particleSceneIdx]();147};148var backParticleAction = function () {149 particleSceneIdx--;150 if (particleSceneIdx < 0)151 particleSceneIdx += particleSceneArr.length;152 return particleSceneArr[particleSceneIdx]();153};154var restartParticleAction = function () {155 return particleSceneArr[particleSceneIdx]();156};157var ParticleDemo = BaseTestLayer.extend({158 _emitter:null,159 _background:null,160 _shapeModeButton:null,161 _textureModeButton:null,162 _isPressed:false,163 setColor:function () {164 },165 ctor:function () {166 this._super(cc.color(0,0,0,255), cc.color(98,99,117,255));167 this._emitter = null;168 if ('touches' in cc.sys.capabilities){169 cc.eventManager.addListener({170 event: cc.EventListener.TOUCH_ALL_AT_ONCE,171 onTouchesBegan:function (touches, event) {172 event.getCurrentTarget()._moveToTouchPoint(touches[0].getLocation());173 },174 onTouchesMoved:function (touches, event) {175 event.getCurrentTarget()._moveToTouchPoint(touches[0].getLocation());176 }177 }, this);178 } else if ('mouse' in cc.sys.capabilities)179 cc.eventManager.addListener({180 event: cc.EventListener.MOUSE,181 onMouseDown: function(event){182 event.getCurrentTarget()._moveToTouchPoint(event.getLocation());183 },184 onMouseMove: function(event){185 if(event.getButton() == cc.EventMouse.BUTTON_LEFT)186 event.getCurrentTarget()._moveToTouchPoint(event.getLocation());187 }188 }, this);189 var s = director.getWinSize();190 var freeBtnNormal = new cc.Sprite(s_MovementMenuItem, cc.rect(0, 23 * 2, 123, 23));191 var freeBtnSelected = new cc.Sprite(s_MovementMenuItem, cc.rect(0, 23, 123, 23));192 var freeBtnDisabled = new cc.Sprite(s_MovementMenuItem, cc.rect(0, 0, 123, 23));193 var relativeBtnNormal = new cc.Sprite(s_MovementMenuItem, cc.rect(123, 23 * 2, 138, 23));194 var relativeBtnSelected = new cc.Sprite(s_MovementMenuItem, cc.rect(123, 23, 138, 23));195 var relativeBtnDisabled = new cc.Sprite(s_MovementMenuItem, cc.rect(123, 0, 138, 23));196 var groupBtnNormal = new cc.Sprite(s_MovementMenuItem, cc.rect(261, 23 * 2, 136, 23));197 var groupBtnSelected = new cc.Sprite(s_MovementMenuItem, cc.rect(261, 23, 136, 23));198 var groupBtnDisabled = new cc.Sprite(s_MovementMenuItem, cc.rect(261, 0, 136, 23));199 var selfPoint = this;200 this._freeMovementButton = new cc.MenuItemSprite(freeBtnNormal, freeBtnSelected, freeBtnDisabled,201 function () {202 selfPoint._emitter.setPositionType(cc.ParticleSystem.TYPE_RELATIVE);203 selfPoint._relativeMovementButton.setVisible(true);204 selfPoint._freeMovementButton.setVisible(false);205 selfPoint._groupMovementButton.setVisible(false);206 });207 this._freeMovementButton.x = 10;208 this._freeMovementButton.y = 150;209 this._freeMovementButton.setAnchorPoint(0, 0);210 this._relativeMovementButton = new cc.MenuItemSprite(relativeBtnNormal, relativeBtnSelected, relativeBtnDisabled,211 function () {212 selfPoint._emitter.setPositionType(cc.ParticleSystem.TYPE_GROUPED);213 selfPoint._relativeMovementButton.setVisible(false);214 selfPoint._freeMovementButton.setVisible(false);215 selfPoint._groupMovementButton.setVisible(true);216 });217 this._relativeMovementButton.setVisible(false);218 this._relativeMovementButton.x = 10;219 this._relativeMovementButton.y = 150;220 this._relativeMovementButton.setAnchorPoint(0, 0);221 this._groupMovementButton = new cc.MenuItemSprite(groupBtnNormal, groupBtnSelected, groupBtnDisabled,222 function () {223 selfPoint._emitter.setPositionType(cc.ParticleSystem.TYPE_FREE);224 selfPoint._relativeMovementButton.setVisible(false);225 selfPoint._freeMovementButton.setVisible(true);226 selfPoint._groupMovementButton.setVisible(false);227 });228 this._groupMovementButton.setVisible(false);229 this._groupMovementButton.x = 10;230 this._groupMovementButton.y = 150;231 this._groupMovementButton.setAnchorPoint(0, 0);232 var spriteNormal = new cc.Sprite(s_shapeModeMenuItem, cc.rect(0, 23 * 2, 115, 23));233 var spriteSelected = new cc.Sprite(s_shapeModeMenuItem, cc.rect(0, 23, 115, 23));234 var spriteDisabled = new cc.Sprite(s_shapeModeMenuItem, cc.rect(0, 0, 115, 23));235 this._shapeModeButton = new cc.MenuItemSprite(spriteNormal, spriteSelected, spriteDisabled,236 function () {237 if (selfPoint._emitter.setDrawMode)238 selfPoint._emitter.setDrawMode(cc.ParticleSystem.TEXTURE_MODE);239 selfPoint._textureModeButton.setVisible(true);240 selfPoint._shapeModeButton.setVisible(false);241 });242 this._shapeModeButton.setVisible(false);243 this._shapeModeButton.x = 10;244 this._shapeModeButton.y = 100;245 this._shapeModeButton.setAnchorPoint(0, 0);246 var spriteNormal_t = new cc.Sprite(s_textureModeMenuItem, cc.rect(0, 23 * 2, 115, 23));247 var spriteSelected_t = new cc.Sprite(s_textureModeMenuItem, cc.rect(0, 23, 115, 23));248 var spriteDisabled_t = new cc.Sprite(s_textureModeMenuItem, cc.rect(0, 0, 115, 23));249 this._textureModeButton = new cc.MenuItemSprite(spriteNormal_t, spriteSelected_t, spriteDisabled_t,250 function () {251 if (selfPoint._emitter.setDrawMode)252 selfPoint._emitter.setDrawMode(cc.ParticleSystem.SHAPE_MODE);253 selfPoint._textureModeButton.setVisible(false);254 selfPoint._shapeModeButton.setVisible(true);255 });256 this._textureModeButton.x = 10;257 this._textureModeButton.y = 100;258 this._textureModeButton.setAnchorPoint(0, 0);259 if ('opengl' in cc.sys.capabilities ) {260 // Shape type is not compatible with JSB261 this._textureModeButton.enabled = false;262 }263 var menu = new cc.Menu( this._shapeModeButton, this._textureModeButton,264 this._freeMovementButton, this._relativeMovementButton, this._groupMovementButton);265 menu.x = 0;266 menu.y = 0;267 this.addChild(menu, 100);268 //TODO269 var labelAtlas = new cc.LabelAtlas("0123456789", s_fpsImages, 12, 32, '.');270 this.addChild(labelAtlas, 100, TAG_LABEL_ATLAS);271 labelAtlas.x = s.width - 66;272 labelAtlas.y = 50;273 // moving background274 this._background = new cc.Sprite(s_back3);275 this.addChild(this._background, 5);276 this._background.x = s.width / 2;277 this._background.y = s.height - 180;278 var move = cc.moveBy(4, cc.p(300, 0));279 var move_back = move.reverse();280 var seq = cc.sequence(move, move_back);281 this._background.runAction(seq.repeatForever());282 this.scheduleUpdate();283 },284 onEnter:function () {285 this._super();286 var pLabel = this.getChildByTag(BASE_TEST_TITLE_TAG);287 pLabel.setString(this.title());288 },289 title:function () {290 return "No title";291 },292 subtitle:function () {293 return "(Tap the Screen)";294 },295 onRestartCallback:function (sender) {296 this._emitter.resetSystem();297 },298 onNextCallback:function (sender) {299 var s = new ParticleTestScene();300 s.addChild(nextParticleAction());301 director.runScene(s);302 },303 onBackCallback:function (sender) {304 var s = new ParticleTestScene();305 s.addChild(backParticleAction());306 director.runScene(s);307 },308 toggleCallback:function (sender) {309 if (this._emitter.getPositionType() == cc.ParticleSystem.TYPE_GROUPED)310 this._emitter.setPositionType(cc.ParticleSystem.TYPE_FREE);311 else if (this._emitter.getPositionType() == cc.ParticleSystem.TYPE_FREE)312 this._emitter.setPositionType(cc.ParticleSystem.TYPE_RELATIVE);313 else if (this._emitter.getPositionType() == cc.ParticleSystem.TYPE_RELATIVE)314 this._emitter.setPositionType(cc.ParticleSystem.TYPE_GROUPED);315 },316 _moveToTouchPoint: function (location) {317 var pos = cc.p(0, 0);318 if (this._background) {319 pos = this._background.convertToWorldSpace(cc.p(0, 0));320 }321 this._emitter.x = location.x - pos.x;322 this._emitter.y = location.y - pos.y;323 },324 update:function (dt) {325 if (this._emitter) {326 var atlas = this.getChildByTag(TAG_LABEL_ATLAS);327 atlas.setString(this._emitter.getParticleCount().toFixed(0));328 }329 },330 setEmitterPosition:function () {331 var sourcePos = this._emitter.getSourcePosition();332 if (sourcePos.x === 0 && sourcePos.y === 0)333 this._emitter.x = 200;334 this._emitter.y = 70;335 },336 // automation337 numberOfPendingTests:function() {338 return ( (particleSceneArr.length-1) - particleSceneIdx );339 },340 getTestNumber:function() {341 return particleSceneIdx;342 }343});344var DemoFirework = ParticleDemo.extend({345 onEnter:function () {346 this._super();347 this._emitter = new cc.ParticleFireworks();348 this._background.addChild(this._emitter, 10);349 this._emitter.texture = cc.textureCache.addImage(s_stars1);350 if (this._emitter.setShapeType)351 this._emitter.setShapeType(cc.ParticleSystem.STAR_SHAPE);352 this.setEmitterPosition();353 },354 title:function () {355 return "ParticleFireworks";356 }357});358var DemoFire = ParticleDemo.extend({359 onEnter:function () {360 this._super();361 this._emitter = new cc.ParticleFire();362 this._background.addChild(this._emitter, 10);363 this._emitter.texture = cc.textureCache.addImage(s_fire);//.pvr"];364 if (this._emitter.setShapeType)365 this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE);366 this.setEmitterPosition();367 },368 title:function () {369 return "ParticleFire";370 }371});372var DemoSun = ParticleDemo.extend({373 onEnter:function () {374 this._super();375 this._emitter = new cc.ParticleSun();376 this._background.addChild(this._emitter, 10);377 this._emitter.texture = cc.textureCache.addImage(s_fire);378 if (this._emitter.setShapeType)379 this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE);380 this.setEmitterPosition();381 },382 title:function () {383 return "ParticleSun";384 }385});386var DemoPause = ParticleDemo.extend({387 onEnter:function () {388 this._super();389 this._emitter = new cc.ParticleSmoke();390 this._background.addChild(this._emitter, 10);391 this._emitter.texture = cc.textureCache.addImage(s_fire);392 if (this._emitter.setShapeType)393 this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE);394 this.setEmitterPosition();395 },396 title:function () {397 return "Pause Particle";398 }399 });400var DemoGalaxy = ParticleDemo.extend({401 onEnter:function () {402 this._super();403 this._emitter = new cc.ParticleGalaxy();404 this._background.addChild(this._emitter, 10);405 this._emitter.texture = cc.textureCache.addImage(s_fire);406 if (this._emitter.setShapeType)407 this._emitter.setShapeType(cc.ParticleSystem.BALL_SHAPE);408 this.setEmitterPosition();409 },410 title:function () {411 return "ParticleGalaxy";412 }413});414var DemoFlower = ParticleDemo.extend({415 _title:"ParticleFlower",416 onEnter:function () {417 this._super();418 this._emitter = new cc.ParticleFlower();419 this._background.addChild(this._emitter, 10);420 this._emitter.texture = cc.textureCache.addImage(s_stars1);421 if (this._emitter.setShapeType)422 this._emitter.setShapeType(cc.ParticleSystem.STAR_SHAPE);423 this.setEmitterPosition();424 },425 title:function () {426 return this._title;427 }428});429var DemoBigFlower = ParticleDemo.extend({430 onEnter:function () {431 this._super();432 this._emitter = new cc.ParticleSystem(50);433 this._background.addChild(this._emitter, 10);434 this._emitter.texture = cc.textureCache.addImage(s_stars1);435 this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE;436 this._emitter.duration = -1;437 // gravity438 this._emitter.gravity = cc.p(0, 0);439 // angle440 this._emitter.angle = 90;441 this._emitter.angleVar = 360;442 // speed of particles443 this._emitter.speed = 160;444 this._emitter.speedVar = 20;445 // radial446 this._emitter.radialAccel = -120;447 this._emitter.radialAccelVar = 0;448 // tangential449 this._emitter.tangentialAccel = 30;450 this._emitter.tangentialAccelVar = 0;451 // emitter position452 this._emitter.x = 160;453 this._emitter.y = 240;454 this._emitter.posVar = cc.p(0, 0);455 // life of particles456 this._emitter.life = 4;457 this._emitter.lifeVar = 1;458 // spin of particles459 this._emitter.startSpin = 0;460 this._emitter.startSizeVar = 0;461 this._emitter.endSpin = 0;462 this._emitter.endSpinVar = 0;463 // color of particles464 this._emitter.startColor = cc.color(128, 128, 128, 255);465 this._emitter.startColorVar = cc.color(128, 128, 128, 255);466 this._emitter.endColor = cc.color(26, 26, 26, 50);467 this._emitter.endColorVar = cc.color(26, 26, 26, 50);468 // size, in pixels469 this._emitter.startSize = 80.0;470 this._emitter.startSizeVar = 40.0;471 this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE;472 // emits per second473 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;474 // additive475 this._emitter.setBlendAdditive(true);476 this.setEmitterPosition();477 },478 title:function () {479 return "ParticleBigFlower";480 }481});482var DemoRotFlower = ParticleDemo.extend({483 onEnter:function () {484 this._super();485 this._emitter = new cc.ParticleSystem(("opengl" in cc.sys.capabilities) ? 300 : 150);486 this._background.addChild(this._emitter, 10);487 this._emitter.texture = cc.textureCache.addImage(s_stars2);488 if (this._emitter.setShapeType)489 this._emitter.setShapeType(cc.ParticleSystem.STAR_SHAPE);490 // duration491 this._emitter.duration = -1;492 // gravity493 this._emitter.gravity = cc.p(0, 0);494 // angle495 this._emitter.angle = 90;496 this._emitter.angleVar = 360;497 // speed of particles498 this._emitter.speed = 160;499 this._emitter.speedVar = 20;500 // radial501 this._emitter.radialAccel = -120;502 this._emitter.radialAccelVar = 0;503 // tangential504 this._emitter.tangentialAccel = 30;505 this._emitter.tangentialAccelVar = 0;506 // emitter position507 this._emitter.x = 160;508 this._emitter.y = 240;509 this._emitter.posVar = cc.p(0, 0);510 // life of particles511 this._emitter.life = 3;512 this._emitter.lifeVar = 1;513 // spin of particles514 this._emitter.startSpin = 0;515 this._emitter.startSpinVar = 0;516 this._emitter.endSpin = 0;517 this._emitter.endSpinVar = 2000;518 this._emitter.startColor = cc.color(128, 128, 128, 255);519 this._emitter.startColorVar = cc.color(128, 128, 128, 255);520 this._emitter.endColor = cc.color(26, 26, 26, 50);521 this._emitter.endColorVar = cc.color(26, 26, 26, 50);522 // size, in pixels523 this._emitter.startSize = 30.0;524 this._emitter.startSizeVar = 0;525 this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE;526 // emits per second527 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;528 // additive529 this._emitter.setBlendAdditive(false);530 this.setEmitterPosition();531 },532 title:function () {533 return "ParticleRotFlower";534 }535});536var DemoMeteor = ParticleDemo.extend({537 onEnter:function () {538 this._super();539 this._emitter = new cc.ParticleMeteor();540 this._background.addChild(this._emitter, 10);541 this._emitter.texture = cc.textureCache.addImage(s_fire);542 this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE;543 this.setEmitterPosition();544 },545 title:function () {546 return "ParticleMeteor";547 }548});549var DemoSpiral = ParticleDemo.extend({550 onEnter:function () {551 this._super();552 this._emitter = new cc.ParticleSpiral();553 this._background.addChild(this._emitter, 10);554 this._emitter.texture = cc.textureCache.addImage(s_fire);555 this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE;556 this.setEmitterPosition();557 },558 title:function () {559 return "ParticleSpiral";560 }561});562var DemoExplosion = ParticleDemo.extend({563 onEnter:function () {564 this._super();565 this._emitter = new cc.ParticleExplosion();566 this._background.addChild(this._emitter, 10);567 this._emitter.texture = cc.textureCache.addImage(s_stars1);568 this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE;569 this._emitter.setAutoRemoveOnFinish(true);570 this.setEmitterPosition();571 },572 onExit: function() {573 this._super();574 },575 title:function () {576 return "ParticleExplosion";577 }578});579var DemoSmoke = ParticleDemo.extend({580 onEnter:function () {581 this._super();582 this._emitter = new cc.ParticleSmoke();583 this._background.addChild(this._emitter, 10);584 this._emitter.texture = cc.textureCache.addImage(s_fire);585 this.setEmitterPosition();586 },587 title:function () {588 return "ParticleSmoke";589 }590});591var DemoSnow = ParticleDemo.extend({592 onEnter:function () {593 this._super();594 this._emitter = new cc.ParticleSnow();595 this._background.addChild(this._emitter, 10);596 this._emitter.life = 3;597 this._emitter.lifeVar = 1;598 // gravity599 this._emitter.gravity = cc.p(0, -10);600 // speed of particles601 this._emitter.speed = 130;602 this._emitter.speedVar = 30;603 var startColor = this._emitter.startColor;604 startColor.r = 230;605 startColor.g = 230;606 startColor.b = 230;607 this._emitter.startColor = startColor;608 var startColorVar = this._emitter.startColorVar;609 startColorVar.b = 26;610 this._emitter.startColorVar = startColorVar;611 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;612 this._emitter.texture = cc.textureCache.addImage(s_snow);613 this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE;614 this.setEmitterPosition();615 },616 title:function () {617 return "ParticleSnow";618 }619});620var DemoRain = ParticleDemo.extend({621 onEnter:function () {622 this._super();623 this._emitter = new cc.ParticleRain();624 this._background.addChild(this._emitter, 10);625 this._emitter.life = 4;626 this._emitter.texture = cc.textureCache.addImage(s_fire);627 this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE;628 this.setEmitterPosition();629 },630 title:function () {631 return "ParticleRain";632 }633});634var DemoModernArt = ParticleDemo.extend({635 onEnter:function () {636 this._super();637 this._emitter = new cc.ParticleSystem(("opengl" in cc.sys.capabilities) ? 1000 : 200);638 this._background.addChild(this._emitter, 10);639 var winSize = director.getWinSize();640 // duration641 this._emitter.duration = -1;642 // gravity643 this._emitter.gravity = cc.p(0, 0);644 // angle645 this._emitter.angle = 0;646 this._emitter.angleVar = 360;647 // radial648 this._emitter.radialAccel = 70;649 this._emitter.radialAccelVar = 10;650 // tangential651 this._emitter.tangentialAccel = 80;652 this._emitter.tangentialAccelVar = 0;653 // speed of particles654 this._emitter.speed = 50;655 this._emitter.speedVar = 10;656 // life of particles657 this._emitter.life = 2.0;658 this._emitter.lifeVar = 0.3;659 // emits per frame660 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;661 // color of particles662 this._emitter.startColor = cc.color(128, 128, 128, 255);663 this._emitter.startColorVar = cc.color(128, 128, 128, 255);664 this._emitter.endColor = cc.color(26, 26, 26, 50);665 this._emitter.endColorVar = cc.color(26, 26, 26, 50);666 // size, in pixels667 this._emitter.startSize = 1.0;668 this._emitter.startSizeVar = 1.0;669 this._emitter.endSize = 32.0;670 this._emitter.endSizeVar = 8.0;671 // texture672 this._emitter.texture = cc.textureCache.addImage(s_fire);673 this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE;674 // additive675 this._emitter.setBlendAdditive(false);676 this.setEmitterPosition();677 },678 title:function () {679 return "Varying size";680 }681});682var DemoRing = ParticleDemo.extend({683 onEnter:function () {684 this._super();685 this._emitter = new cc.ParticleFlower();686 this._background.addChild(this._emitter, 10);687 this._emitter.texture = cc.textureCache.addImage(s_stars1);688 this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE;689 this._emitter.lifeVar = 0;690 this._emitter.life = 10;691 this._emitter.speed = 100;692 this._emitter.speedVar = 0;693 this._emitter.emissionRate = 10000;694 this.setEmitterPosition();695 },696 title:function () {697 return "Ring Demo";698 }699});700var ParallaxParticle = ParticleDemo.extend({701 onEnter:function () {702 this._super();703 this._background.getParent().removeChild(this._background, true);704 this._background = null;705 //TODO706 var p = new cc.ParallaxNode();707 this.addChild(p, 5);708 var p1 = new cc.Sprite(s_back3);709 var p2 = new cc.Sprite(s_back3);710 p.addChild(p1, 1, cc.p(0.5, 1), cc.p(0, 250));711 p.addChild(p2, 2, cc.p(1.5, 1), cc.p(0, 50));712 this._emitter = new cc.ParticleFlower();713 this._emitter.texture = cc.textureCache.addImage(s_fire);714 p1.addChild(this._emitter, 10);715 this._emitter.x = 250;716 this._emitter.y = 200;717 var par = new cc.ParticleSun();718 p2.addChild(par, 10);719 par.texture = cc.textureCache.addImage(s_fire);720 var move = cc.moveBy(4, cc.p(300, 0));721 var move_back = move.reverse();722 var seq = cc.sequence(move, move_back);723 p.runAction(seq.repeatForever());724 },725 title:function () {726 return "Parallax + Particles";727 }728});729var DemoParticleFromFile = ParticleDemo.extend({730 _title:"",731 ctor:function (filename) {732 this._super();733 this._title = filename;734 },735 onEnter:function () {736 this._super();737 this.setColor(cc.color(0, 0, 0));738 this.removeChild(this._background, true);739 this._background = null;740 this._emitter = new cc.ParticleSystem(s_resprefix + "Particles/" + this._title + ".plist");741 // test create from a object742 // var plistData = jsb.fileUtils.getValueMapFromFile(s_resprefix + "Particles/" + this._title + ".plist");743 // this._emitter = new cc.ParticleSystem(plistData);744 this.addChild(this._emitter, 10);745 if (this._title == "Flower") {746 this._emitter.shapeType = cc.ParticleSystem.STAR_SHAPE;747 }//else if( this._title == "Upsidedown"){748 // this._emitter.setDrawMode(cc.ParticleSystem.TEXTURE_MODE);749 //}750 this.setEmitterPosition();751 },752 setEmitterPosition:function () {753 var sourcePos = this._emitter.getSourcePosition();754 if (sourcePos.x === 0 && sourcePos.y === 0)755 this._emitter.x = director.getWinSize().width / 2;756 this._emitter.y = director.getWinSize().height / 2 - 50;757 },758 title:function () {759 return this._title;760 }761});762var RadiusMode1 = ParticleDemo.extend({763 onEnter:function () {764 this._super();765 this.setColor(cc.color(0, 0, 0));766 this.removeChild(this._background, true);767 this._background = null;768 this._emitter = new cc.ParticleSystem(100);769 this.addChild(this._emitter, 10);770 this._emitter.texture = cc.textureCache.addImage(s_starsGrayscale);771 // duration772 this._emitter.duration = cc.ParticleSystem.DURATION_INFINITY;773 // radius mode774 this._emitter.emitterMode = cc.ParticleSystem.MODE_RADIUS;775 // radius mode: start and end radius in pixels776 this._emitter.startRadius = 0;777 this._emitter.startRadiusVar = 0;778 this._emitter.endRadius = 160;779 this._emitter.endRadiusVar = 0;780 // radius mode: degrees per second781 this._emitter.rotatePerS = 180;782 this._emitter.rotatePerSVar = 0;783 // angle784 this._emitter.angle = 90;785 this._emitter.angleVar = 0;786 // emitter position787 var size = director.getWinSize();788 this._emitter.x = size.width / 2;789 this._emitter.y = size.height / 2;790 this._emitter.posVar = cc.p(0, 0);791 // life of particles792 this._emitter.life = 5;793 this._emitter.lifeVar = 0;794 // spin of particles795 this._emitter.startSpin = 0;796 this._emitter.startSpinVar = 0;797 this._emitter.endSpin = 0;798 this._emitter.endSpinVar = 0;799 // color of particles800 this._emitter.startColor = cc.color(128, 128, 128, 255);801 this._emitter.startColorVar = cc.color(128, 128, 128, 255);802 this._emitter.endColor = cc.color(26, 26, 26, 50);803 this._emitter.endColorVar = cc.color(26, 26, 26, 50);804 // size, in pixels805 this._emitter.startSize = 32;806 this._emitter.startSizeVar = 0;807 this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE;808 // emits per second809 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;810 // additive811 this._emitter.setBlendAdditive(false);812 },813 title:function () {814 return "Radius Mode: Spiral";815 }816});817var RadiusMode2 = ParticleDemo.extend({818 onEnter:function () {819 this._super();820 this.color = cc.color(0, 0, 0);821 this.removeChild(this._background, true);822 this._background = null;823 this._emitter = new cc.ParticleSystem(100);824 this.addChild(this._emitter, 10);825 this._emitter.texture = cc.textureCache.addImage(s_starsGrayscale);826 // duration827 this._emitter.duration = cc.ParticleSystem.DURATION_INFINITY;828 // radius mode829 this._emitter.emitterMode = cc.ParticleSystem.MODE_RADIUS;830 // radius mode: start and end radius in pixels831 this._emitter.startRadius = 100;832 this._emitter.startRadiusVar = 0;833 this._emitter.endRadius = cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS;834 this._emitter.endRadiusVar = 0;835 // radius mode: degrees per second836 this._emitter.rotatePerS = 45;837 this._emitter.rotatePerSVar = 0;838 // angle839 this._emitter.angle = 90;840 this._emitter.angleVar = 0;841 // emitter position842 var size = director.getWinSize();843 this._emitter.x = size.width / 2;844 this._emitter.y = size.height / 2;845 this._emitter.posVar = cc.p(0, 0);846 // life of particles847 this._emitter.life = 4;848 this._emitter.lifeVar = 0;849 // spin of particles850 this._emitter.startSpin = 0;851 this._emitter.startSpinVar = 0;852 this._emitter.endSpin = 0;853 this._emitter.endSpinVar = 0;854 // color of particles855 this._emitter.startColor = cc.color(128, 128, 128, 255);856 this._emitter.startColorVar = cc.color(128, 128, 128, 255);857 this._emitter.endColor = cc.color(26, 26, 26, 50);858 this._emitter.endColorVar = cc.color(26, 26, 26, 50);859 // size, in pixels860 this._emitter.startSize = 32;861 this._emitter.startSizeVar = 0;862 this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE;863 // emits per second864 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;865 // additive866 this._emitter.setBlendAdditive(false);867 },868 title:function () {869 return "Radius Mode: Semi Circle";870 }871});872var Issue704 = ParticleDemo.extend({873 onEnter:function () {874 this._super();875 this.color = cc.color(0, 0, 0);876 this.removeChild(this._background, true);877 this._background = null;878 this._emitter = new cc.ParticleSystem(100);879 this.addChild(this._emitter, 10);880 this._emitter.texture = cc.textureCache.addImage(s_fire);881 this._emitter.shapeType = cc.ParticleSystem.BALL_SHAPE;882 // duration883 this._emitter.duration = cc.ParticleSystem.DURATION_INFINITY;884 // radius mode885 this._emitter.emitterMode = cc.ParticleSystem.MODE_RADIUS;886 // radius mode: start and end radius in pixels887 this._emitter.startRadius = 50;888 this._emitter.startRadiusVar = 0;889 this._emitter.endRadius = cc.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS;890 this._emitter.endRadiusVar = 0;891 // radius mode: degrees per second892 this._emitter.rotatePerS = 0;893 this._emitter.rotatePerSVar = 0;894 // angle895 this._emitter.angle = 90;896 this._emitter.angleVar = 0;897 // emitter position898 var size = director.getWinSize();899 this._emitter.x = size.width / 2;900 this._emitter.y = size.height / 2;901 this._emitter.posVar = cc.p(0, 0);902 // life of particles903 this._emitter.life = 5;904 this._emitter.lifeVar = 0;905 // spin of particles906 this._emitter.startSpin = 0;907 this._emitter.startSpinVar = 0;908 this._emitter.endSpin = 0;909 this._emitter.endSpinVar = 0;910 // color of particles911 this._emitter.startColor = cc.color(128, 128, 128, 255);912 this._emitter.startColorVar = cc.color(128, 128, 128, 255);913 this._emitter.endColor = cc.color(26, 26, 26, 50);914 this._emitter.endColorVar = cc.color(26, 26, 26, 50);915 // size, in pixels916 this._emitter.startSize = 16;917 this._emitter.startSizeVar = 0;918 this._emitter.endSize = cc.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE;919 // emits per second920 this._emitter.emissionRate = this._emitter.totalParticles / this._emitter.life;921 // additive922 this._emitter.setBlendAdditive(false);923 var rot = cc.rotateBy(16, 360);924 this._emitter.runAction(rot.repeatForever());925 },926 title:function () {927 return "Issue 704. Free + Rot";928 },929 subtitle:function () {930 return "Emitted particles should not rotate";931 }932});933var Issue870 = ParticleDemo.extend({934 _index:0,935 onEnter:function () {936 this._super();937 this.setColor(cc.color(0, 0, 0));938 this.removeChild(this._background, true);939 this._background = null;940 var system = new cc.ParticleSystem(s_resprefix + "Particles/SpinningPeas.plist");941 system.setTextureWithRect(cc.textureCache.addImage(s_particles), cc.rect(0, 0, 32, 32));942 this.addChild(system, 10);943 this._emitter = system;944 this._emitter.drawMode = cc.ParticleSystem.TEXTURE_MODE;945 this._emitter.x = director.getWinSize().width / 2;946 this._emitter.y = director.getWinSize().height / 2 - 50;947 this._index = 0;948 this.schedule(this.updateQuads, 2.0);949 },950 title:function () {951 return "Issue 870. SubRect";952 },953 subtitle:function () {954 return "Every 2 seconds the particle should change";955 },956 updateQuads:function (dt) {957 this._index = (this._index + 1) % 4;958 var rect = cc.rect(this._index * 32, 0, 32, 32);959 this._emitter.setTextureWithRect(this._emitter.texture, rect);960 }961});962var ParticleBatchTest = ParticleDemo.extend({963 _index:0,964 onEnter:function () {965 this._super();966 var emitter1 = new cc.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist');967 emitter1.startColor = cc.color(255, 0, 0, 255);968 var emitter2 = new cc.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist');969 emitter2.startColor = cc.color(0, 255, 0, 255);970 var emitter3 = new cc.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist');971 emitter3.startColor = cc.color(0, 0, 255, 255);972 emitter1.x = winSize.width / 1.25;973 emitter1.y = winSize.height / 1.25;974 emitter2.x = winSize.width / 2;975 emitter2.y = winSize.height / 2;976 emitter3.x = winSize.width / 4;977 emitter3.y = winSize.height / 4;978 var batch = new cc.ParticleBatchNode(emitter1.texture);979 batch.addChild(emitter1);980 batch.addChild(emitter2);981 batch.addChild(emitter3);982 this.addChild(batch, 10);983 // to be able to use "reset" button984 this.removeChild(this._background, true);985 this._background = null;986 this._emitter = emitter1;987 },988 title:function () {989 return "Particle Batch Test";990 },991 subtitle:function () {992 return "You should 3 particles. They are batched";993 }994});995var ParticleResizeTest = ParticleDemo.extend({996 _index:0,997 onEnter:function () {998 this._super();999 var emitter1 = new cc.ParticleSystem( s_resprefix + 'Particles/LavaFlow.plist');1000 emitter1.x = winSize.width/2;1001 emitter1.y = winSize.height/2;1002 this.addChild(emitter1);1003 this.schedule( this.onResizeParticle50, 2 );1004 // to be able to use "reset" button1005 this.removeChild(this._background, true);1006 this._background = null;1007 this._emitter = emitter1;1008 },1009 onResizeParticle50:function(dt) {1010 this._emitter.totalParticles = 50;1011 this.scheduleOnce( this.onResizeParticle400, 1);1012 },1013 onResizeParticle400:function(dt) {1014 this._emitter.totalParticles = 400;1015 },1016 title:function () {1017 return "Particle Resize Test";1018 },1019 subtitle:function () {1020 return "In 2 seconds, the emitter should have only 15 particles. Shall not crash.";1021 }...

Full Screen

Full Screen

emittermixin.js

Source:emittermixin.js Github

copy

Full Screen

1/**2 * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license4 */5/**6 * @module utils/dom/emittermixin7 */8import { default as EmitterMixin, _getEmitterListenedTo, _setEmitterId } from '../emittermixin';9import uid from '../uid';10import isNode from './isnode';11import isWindow from './iswindow';12import { extend } from 'lodash-es';13/**14 * Mixin that injects the DOM events API into its host. It provides the API15 * compatible with {@link module:utils/emittermixin~EmitterMixin}.16 *17 * DOM emitter mixin is by default available in the {@link module:ui/view~View} class,18 * but it can also be mixed into any other class:19 *20 * import mix from '../utils/mix.js';21 * import DomEmitterMixin from '../utils/dom/emittermixin.js';22 *23 * class SomeView {}24 * mix( SomeView, DomEmitterMixin );25 *26 * const view = new SomeView();27 * view.listenTo( domElement, ( evt, domEvt ) => {28 * console.log( evt, domEvt );29 * } );30 *31 * @mixin EmitterMixin32 * @mixes module:utils/emittermixin~EmitterMixin33 * @implements module:utils/dom/emittermixin~Emitter34 */35const DomEmitterMixin = extend( {}, EmitterMixin, {36 /**37 * Registers a callback function to be executed when an event is fired in a specific Emitter or DOM Node.38 * It is backwards compatible with {@link module:utils/emittermixin~EmitterMixin#listenTo}.39 *40 * @param {module:utils/emittermixin~Emitter|Node} emitter The object that fires the event.41 * @param {String} event The name of the event.42 * @param {Function} callback The function to be called on event.43 * @param {Object} [options={}] Additional options.44 * @param {module:utils/priorities~PriorityString|Number} [options.priority='normal'] The priority of this event callback. The higher45 * the priority value the sooner the callback will be fired. Events having the same priority are called in the46 * order they were added.47 * @param {Boolean} [options.useCapture=false] Indicates that events of this type will be dispatched to the registered48 * listener before being dispatched to any EventTarget beneath it in the DOM tree.49 * @param {Boolean} [options.usePassive=false] Indicates that the function specified by listener will never call preventDefault()50 * and prevents blocking browser's main thread by this event handler.51 */52 listenTo( emitter, ...rest ) {53 // Check if emitter is an instance of DOM Node. If so, replace the argument with54 // corresponding ProxyEmitter (or create one if not existing).55 if ( isNode( emitter ) || isWindow( emitter ) ) {56 const proxy = this._getProxyEmitter( emitter ) || new ProxyEmitter( emitter );57 proxy.attach( ...rest );58 emitter = proxy;59 }60 // Execute parent class method with Emitter (or ProxyEmitter) instance.61 EmitterMixin.listenTo.call( this, emitter, ...rest );62 },63 /**64 * Stops listening for events. It can be used at different levels:65 * It is backwards compatible with {@link module:utils/emittermixin~EmitterMixin#listenTo}.66 *67 * * To stop listening to a specific callback.68 * * To stop listening to a specific event.69 * * To stop listening to all events fired by a specific object.70 * * To stop listening to all events fired by all object.71 *72 * @param {module:utils/emittermixin~Emitter|Node} [emitter] The object to stop listening to. If omitted, stops it for all objects.73 * @param {String} [event] (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it74 * for all events from `emitter`.75 * @param {Function} [callback] (Requires the `event`) The function to be removed from the call list for the given76 * `event`.77 */78 stopListening( emitter, event, callback ) {79 // Check if emitter is an instance of DOM Node. If so, replace the argument with corresponding ProxyEmitter.80 if ( isNode( emitter ) || isWindow( emitter ) ) {81 const proxy = this._getProxyEmitter( emitter );82 // Element has no listeners.83 if ( !proxy ) {84 return;85 }86 emitter = proxy;87 }88 // Execute parent class method with Emitter (or ProxyEmitter) instance.89 EmitterMixin.stopListening.call( this, emitter, event, callback );90 if ( emitter instanceof ProxyEmitter ) {91 emitter.detach( event );92 }93 },94 /**95 * Retrieves ProxyEmitter instance for given DOM Node residing in this Host.96 *97 * @private98 * @param {Node} node DOM Node of the ProxyEmitter.99 * @returns {module:utils/dom/emittermixin~ProxyEmitter} ProxyEmitter instance or null.100 */101 _getProxyEmitter( node ) {102 return _getEmitterListenedTo( this, getNodeUID( node ) );103 }104} );105export default DomEmitterMixin;106/**107 * Creates a ProxyEmitter instance. Such an instance is a bridge between a DOM Node firing events108 * and any Host listening to them. It is backwards compatible with {@link module:utils/emittermixin~EmitterMixin#on}.109 *110 * listenTo( click, ... )111 * +-----------------------------------------+112 * | stopListening( ... ) |113 * +----------------------------+ | addEventListener( click, ... )114 * | Host | | +---------------------------------------------+115 * +----------------------------+ | | removeEventListener( click, ... ) |116 * | _listeningTo: { | +----------v-------------+ |117 * | UID: { | | ProxyEmitter | |118 * | emitter: ProxyEmitter, | +------------------------+ +------------v----------+119 * | callbacks: { | | events: { | | Node (HTMLElement) |120 * | click: [ callbacks ] | | click: [ callbacks ] | +-----------------------+121 * | } | | }, | | data-ck-expando: UID |122 * | } | | _domNode: Node, | +-----------------------+123 * | } | | _domListeners: {}, | |124 * | +------------------------+ | | _emitterId: UID | |125 * | | DomEmitterMixin | | +--------------^---------+ |126 * | +------------------------+ | | | |127 * +--------------^-------------+ | +---------------------------------------------+128 * | | click (DOM Event)129 * +-----------------------------------------+130 * fire( click, DOM Event )131 *132 * @mixes module:utils/emittermixin~EmitterMixin133 * @implements module:utils/dom/emittermixin~Emitter134 * @private135 */136class ProxyEmitter {137 /**138 * @param {Node} node DOM Node that fires events.139 * @returns {Object} ProxyEmitter instance bound to the DOM Node.140 */141 constructor( node ) {142 // Set emitter ID to match DOM Node "expando" property.143 _setEmitterId( this, getNodeUID( node ) );144 // Remember the DOM Node this ProxyEmitter is bound to.145 this._domNode = node;146 }147}148extend( ProxyEmitter.prototype, EmitterMixin, {149 /**150 * Collection of native DOM listeners.151 *152 * @private153 * @member {Object} module:utils/dom/emittermixin~ProxyEmitter#_domListeners154 */155 /**156 * Registers a callback function to be executed when an event is fired.157 *158 * It attaches a native DOM listener to the DOM Node. When fired,159 * a corresponding Emitter event will also fire with DOM Event object as an argument.160 *161 * @method module:utils/dom/emittermixin~ProxyEmitter#attach162 * @param {String} event The name of the event.163 * @param {Function} callback The function to be called on event.164 * @param {Object} [options={}] Additional options.165 * @param {Boolean} [options.useCapture=false] Indicates that events of this type will be dispatched to the registered166 * listener before being dispatched to any EventTarget beneath it in the DOM tree.167 * @param {Boolean} [options.usePassive=false] Indicates that the function specified by listener will never call preventDefault()168 * and prevents blocking browser's main thread by this event handler.169 */170 attach( event, callback, options = {} ) {171 // If the DOM Listener for given event already exist it is pointless172 // to attach another one.173 if ( this._domListeners && this._domListeners[ event ] ) {174 return;175 }176 const listenerOptions = {177 capture: !!options.useCapture,178 passive: !!options.usePassive179 };180 const domListener = this._createDomListener( event, listenerOptions );181 // Attach the native DOM listener to DOM Node.182 this._domNode.addEventListener( event, domListener, listenerOptions );183 if ( !this._domListeners ) {184 this._domListeners = {};185 }186 // Store the native DOM listener in this ProxyEmitter. It will be helpful187 // when stopping listening to the event.188 this._domListeners[ event ] = domListener;189 },190 /**191 * Stops executing the callback on the given event.192 *193 * @method module:utils/dom/emittermixin~ProxyEmitter#detach194 * @param {String} event The name of the event.195 */196 detach( event ) {197 let events;198 // Remove native DOM listeners which are orphans. If no callbacks199 // are awaiting given event, detach native DOM listener from DOM Node.200 // See: {@link attach}.201 if ( this._domListeners[ event ] && ( !( events = this._events[ event ] ) || !events.callbacks.length ) ) {202 this._domListeners[ event ].removeListener();203 }204 },205 /**206 * Creates a native DOM listener callback. When the native DOM event207 * is fired it will fire corresponding event on this ProxyEmitter.208 * Note: A native DOM Event is passed as an argument.209 *210 * @private211 * @method module:utils/dom/emittermixin~ProxyEmitter#_createDomListener212 * @param {String} event The name of the event.213 * @param {Object} [options] Additional options.214 * @param {Boolean} [options.capture=false] Indicates whether the listener was created for capturing event.215 * @param {Boolean} [options.passive=false] Indicates that the function specified by listener will never call preventDefault()216 * and prevents blocking browser's main thread by this event handler.217 * @returns {Function} The DOM listener callback.218 */219 _createDomListener( event, options ) {220 const domListener = domEvt => {221 this.fire( event, domEvt );222 };223 // Supply the DOM listener callback with a function that will help224 // detach it from the DOM Node, when it is no longer necessary.225 // See: {@link detach}.226 domListener.removeListener = () => {227 this._domNode.removeEventListener( event, domListener, options );228 delete this._domListeners[ event ];229 };230 return domListener;231 }232} );233// Gets an unique DOM Node identifier. The identifier will be set if not defined.234//235// @private236// @param {Node} node237// @returns {String} UID for given DOM Node.238function getNodeUID( node ) {239 return node[ 'data-ck-expando' ] || ( node[ 'data-ck-expando' ] = uid() );240}241/**242 * Interface representing classes which mix in {@link module:utils/dom/emittermixin~EmitterMixin}.243 *244 * @interface Emitter...

Full Screen

Full Screen

test_eventemitter_basic.js

Source:test_eventemitter_basic.js Github

copy

Full Screen

1/* Any copyright is dedicated to the Public Domain.2 http://creativecommons.org/publicdomain/zero/1.0/ */3"use strict";4const {5 ConsoleAPIListener,6} = require("devtools/server/actors/webconsole/listeners/console-api");7const EventEmitter = require("devtools/shared/event-emitter");8const hasMethod = (target, method) =>9 method in target && typeof target[method] === "function";10/**11 * Each method of this object is a test; tests can be synchronous or asynchronous:12 *13 * 1. Plain functions are synchronous tests.14 * 2. methods with `async` keyword are asynchronous tests.15 * 3. methods with `done` as argument are asynchronous tests (`done` needs to be called to16 * finish the test).17 */18const TESTS = {19 testEventEmitterCreation() {20 const emitter = getEventEmitter();21 const isAnEmitter = emitter instanceof EventEmitter;22 ok(emitter, "We have an event emitter");23 ok(24 hasMethod(emitter, "on") &&25 hasMethod(emitter, "off") &&26 hasMethod(emitter, "once") &&27 !hasMethod(emitter, "decorate") &&28 !hasMethod(emitter, "count"),29 `Event Emitter ${30 isAnEmitter ? "instance" : "mixin"31 } has the expected methods.`32 );33 },34 testEmittingEvents(done) {35 const emitter = getEventEmitter();36 let beenHere1 = false;37 let beenHere2 = false;38 function next(str1, str2) {39 equal(str1, "abc", "Argument 1 is correct");40 equal(str2, "def", "Argument 2 is correct");41 ok(!beenHere1, "first time in next callback");42 beenHere1 = true;43 emitter.off("next", next);44 emitter.emit("next");45 emitter.once("onlyonce", onlyOnce);46 emitter.emit("onlyonce");47 emitter.emit("onlyonce");48 }49 function onlyOnce() {50 ok(!beenHere2, '"once" listener has been called once');51 beenHere2 = true;52 emitter.emit("onlyonce");53 done();54 }55 emitter.on("next", next);56 emitter.emit("next", "abc", "def");57 },58 testThrowingExceptionInListener(done) {59 const emitter = getEventEmitter();60 const listener = new ConsoleAPIListener(null, {61 onConsoleAPICall(message) {62 equal(message.level, "error");63 equal(message.arguments[0], "foo: bar");64 listener.destroy();65 done();66 },67 });68 listener.init();69 function throwListener() {70 emitter.off("throw-exception");71 throw Object.create({72 toString: () => "foo",73 stack: "bar",74 });75 }76 emitter.on("throw-exception", throwListener);77 emitter.emit("throw-exception");78 },79 testKillItWhileEmitting(done) {80 const emitter = getEventEmitter();81 const c1 = () => ok(true, "c1 called");82 const c2 = () => {83 ok(true, "c2 called");84 emitter.off("tick", c3);85 };86 const c3 = () => ok(false, "c3 should not be called");87 const c4 = () => {88 ok(true, "c4 called");89 done();90 };91 emitter.on("tick", c1);92 emitter.on("tick", c2);93 emitter.on("tick", c3);94 emitter.on("tick", c4);95 emitter.emit("tick");96 },97 testOffAfterOnce() {98 const emitter = getEventEmitter();99 let enteredC1 = false;100 const c1 = () => (enteredC1 = true);101 emitter.once("oao", c1);102 emitter.off("oao", c1);103 emitter.emit("oao");104 ok(!enteredC1, "c1 should not be called");105 },106 testPromise() {107 const emitter = getEventEmitter();108 const p = emitter.once("thing");109 // Check that the promise is only resolved once event though we110 // emit("thing") more than once111 let firstCallbackCalled = false;112 const check1 = p.then(arg => {113 equal(firstCallbackCalled, false, "first callback called only once");114 firstCallbackCalled = true;115 equal(arg, "happened", "correct arg in promise");116 return "rval from c1";117 });118 emitter.emit("thing", "happened", "ignored");119 // Check that the promise is resolved asynchronously120 let secondCallbackCalled = false;121 const check2 = p.then(arg => {122 ok(true, "second callback called");123 equal(arg, "happened", "correct arg in promise");124 secondCallbackCalled = true;125 equal(arg, "happened", "correct arg in promise (a second time)");126 return "rval from c2";127 });128 // Shouldn't call any of the above listeners129 emitter.emit("thing", "trashinate");130 // Check that we can still separate events with different names131 // and that it works with no parameters132 const pfoo = emitter.once("foo");133 const pbar = emitter.once("bar");134 const check3 = pfoo.then(arg => {135 ok(arg === undefined, "no arg for foo event");136 return "rval from c3";137 });138 pbar.then(() => {139 ok(false, "pbar should not be called");140 });141 emitter.emit("foo");142 equal(secondCallbackCalled, false, "second callback not called yet");143 return Promise.all([check1, check2, check3]).then(args => {144 equal(args[0], "rval from c1", "callback 1 done good");145 equal(args[1], "rval from c2", "callback 2 done good");146 equal(args[2], "rval from c3", "callback 3 done good");147 });148 },149 // This API is only provided for backward compatibility reasons with the old SDK150 // event-emitter.151 // !!! This API will be removed by Bug 1391261.152 testWildcard() {153 const emitter = getEventEmitter();154 const received = [];155 const listener = (...args) => received.push(args);156 emitter.on("*", listener);157 emitter.emit("a", 1);158 equal(received.length, 1, "the listener was triggered once");159 equal(received[0].length, 2, "the listener was called with 2 arguments");160 equal(received[0][0], "a", "first argument is the event name");161 equal(received[0][1], 1, "additional arguments are forwarded");162 emitter.emit("*", "wildcard");163 equal(received.length, 2, "the listener was only triggered once");164 equal(165 received[1].length,166 1,167 "the listener was called with only 1 argument"168 );169 equal(received[1][0], "wildcard", "first argument is the actual argument");170 emitter.emit("other", "arg1", "arg2");171 equal(received.length, 3, "the listener was triggered once");172 equal(173 received[2].length,174 3,175 "the listener was called with only 1 argument"176 );177 equal(received[2][0], "other", "first argument is the event name");178 equal(received[2][1], "arg1", "additional arguments are forwarded");179 equal(received[2][2], "arg2", "additional arguments are forwarded");180 emitter.off("*", listener);181 emitter.emit("a");182 emitter.emit("*");183 equal(received.length, 3, "the listener was not called anymore");184 },185 testClearEvents() {186 const emitter = getEventEmitter();187 const received = [];188 const listener = (...args) => received.push(args);189 emitter.on("a", listener);190 emitter.on("b", listener);191 emitter.on("c", listener);192 emitter.emit("a", 1);193 emitter.emit("b", 1);194 emitter.emit("c", 1);195 equal(received.length, 3, "the listener was triggered three times");196 emitter.clearEvents();197 emitter.emit("a", 1);198 emitter.emit("b", 1);199 emitter.emit("c", 1);200 equal(received.length, 3, "the listener was not called after clearEvents");201 },202};203/**204 * Create a runnable tests based on the tests descriptor given.205 *206 * @param {Object} tests207 * The tests descriptor object, contains the tests to run.208 */209const runnable = tests =>210 async function() {211 for (const name of Object.keys(tests)) {212 info(name);213 if (tests[name].length === 1) {214 await new Promise(resolve => tests[name](resolve));215 } else {216 await tests[name]();217 }218 }219 };220// We want to run the same tests for both an instance of `EventEmitter` and an object221// decorate with EventEmitter; therefore we create two strategies (`createNewEmitter` and222// `decorateObject`) and a factory (`getEventEmitter`), where the factory is the actual223// function used in the tests.224const createNewEmitter = () => new EventEmitter();225const decorateObject = () => EventEmitter.decorate({});226// First iteration of the tests with a new instance of `EventEmitter`.227let getEventEmitter = createNewEmitter;228add_task(runnable(TESTS));229// Second iteration of the tests with an object decorate using `EventEmitter`230add_task(() => (getEventEmitter = decorateObject));...

Full Screen

Full Screen

emitter-queue.js

Source:emitter-queue.js Github

copy

Full Screen

1'use strict';2var Code = require('code');3var Lab = require('lab');4var lab = (exports.lab = Lab.script());5var expect = Code.expect;6var describe = lab.describe;7var it = lab.it;8describe('EmitterQueue', function() {9 var EventEmitter = require('events').EventEmitter;10 var EmitterQueue = require('../lib/emitter-queue');11 describe('.on(event, fn)', function() {12 it('should add listeners', function(done) {13 var emitter = new EmitterQueue();14 var calls = [];15 emitter.on('foo', function(val, next) {16 calls.push('one', val);17 next();18 });19 emitter.on('foo', function(val, next) {20 calls.push('two', val);21 next();22 });23 emitter.onceDrain(function() {24 expect(calls).to.deep.equal(['one', 1, 'two', 1, 'one', 2, 'two', 2]);25 done();26 });27 emitter.emit('foo', 1);28 emitter.emit('bar', 1);29 emitter.emit('foo', 2);30 });31 });32 describe('.pre(fn)', function() {33 it('should add pre listeners', function(done) {34 var emitter = new EmitterQueue();35 var calls = [];36 emitter.pre(function(event, val, next) {37 calls.push(event, val);38 next();39 });40 emitter.on('foo', function(val, next) {41 calls.push('bar', val);42 next();43 });44 emitter.onceDrain(function() {45 expect(calls).to.deep.equal(['foo', 1, 'bar', 1, 'foo', 2, 'bar', 2]);46 done();47 });48 emitter.emit('foo', 1);49 emitter.emit('bar', 1);50 emitter.emit('foo', 2);51 });52 });53 describe('.pre([fn, fn])', function() {54 it('should add pre listeners', function(done) {55 var emitter = new EmitterQueue();56 var calls = [];57 emitter.pre([58 function(event, val, next) {59 calls.push(event);60 next();61 },62 function(event, val, next) {63 calls.push(val);64 next();65 }66 ]);67 emitter.on('foo', function(val, next) {68 calls.push('bar', val);69 next();70 });71 emitter.onceDrain(function() {72 expect(calls).to.deep.equal(['foo', 1, 'bar', 1, 'foo', 2, 'bar', 2]);73 done();74 });75 emitter.emit('foo', 1);76 emitter.emit('bar', 1);77 emitter.emit('foo', 2);78 });79 });80 describe('.post(fn)', function() {81 it('should add post listeners', function(done) {82 var emitter = new EmitterQueue();83 var calls = [];84 emitter.post(function(event, val, next) {85 calls.push(event, val);86 next();87 });88 emitter.on('foo', function(val, next) {89 calls.push('bar', val);90 next();91 });92 emitter.onceDrain(function() {93 expect(calls).to.deep.equal(['bar', 1, 'foo', 1, 'bar', 2, 'foo', 2]);94 done();95 });96 emitter.emit('foo', 1);97 emitter.emit('bar', 1);98 emitter.emit('foo', 2);99 });100 });101 describe('.post([fn,fn])', function() {102 it('should add post listeners', function(done) {103 var emitter = new EmitterQueue();104 var calls = [];105 emitter.post([106 function(event, val, next) {107 calls.push(event);108 next();109 },110 function(event, val, next) {111 calls.push(val);112 next();113 }114 ]);115 emitter.on('foo', function(val, next) {116 calls.push('bar', val);117 next();118 });119 emitter.onceDrain(function() {120 expect(calls).to.deep.equal(['bar', 1, 'foo', 1, 'bar', 2, 'foo', 2]);121 done();122 });123 emitter.emit('foo', 1);124 emitter.emit('bar', 1);125 emitter.emit('foo', 2);126 });127 });128 describe('.post(fn)', function() {129 it('should add post listeners', function(done) {130 var emitter = new EmitterQueue();131 var calls = [];132 emitter.post(function(event, val, next) {133 calls.push(event, val);134 next();135 });136 emitter.on('foo', function(val, next) {137 calls.push('bar', val);138 next();139 });140 emitter.onceDrain(function() {141 expect(calls).to.deep.equal(['bar', 1, 'foo', 1, 'bar', 2, 'foo', 2]);142 done();143 });144 emitter.emit('foo', 1);145 emitter.emit('bar', 1);146 emitter.emit('foo', 2);147 });148 });149 describe('.kill()', function() {150 it('should kill queued events', function(done) {151 var emitter = new EmitterQueue();152 emitter.on('foo', function(val, next) {153 expect(true).to.not.be.true();154 done();155 next();156 });157 emitter.on('bar', function(val, next) {158 done();159 next();160 });161 emitter.emit('foo');162 emitter.kill();163 emitter.emit('bar');164 });165 });166 describe('new EmitterQueue(source)', function() {167 it('should emit events from source', function(done) {168 var source = new EventEmitter();169 var emitter = new EmitterQueue(source);170 var calls = [];171 emitter.on('foo', function(val, next) {172 calls.push('one', val);173 next();174 });175 emitter.on('foo', function(val, next) {176 calls.push('two', val);177 next();178 });179 emitter.onceDrain(function() {180 expect(calls).to.deep.equal(['one', 1, 'two', 1, 'one', 2, 'two', 2]);181 done();182 });183 source.emit('foo', 1);184 source.emit('bar', 1);185 source.emit('foo', 2);186 });187 });...

Full Screen

Full Screen

EventEmitter.test.js

Source:EventEmitter.test.js Github

copy

Full Screen

1const _ = require('lodash');2const chai = require('chai');3const expect = chai.expect;4const sinon = require('sinon');5const sinonChai = require('sinon-chai');6chai.use(sinonChai);7const dir = process['test-dir'] || '../../src';8const EventEmitter = require(dir + '/EventEmitter');9describe('EventEmitter', function() {10 describe('#constructor()', function() {11 it('should subclass EventEmitter', function() {12 expect((new EventEmitter()).emit).to.be.a('function');13 });14 it('should allow options to set max # of listeners', sinon.test(function() {15 this.spy(EventEmitter.prototype, 'setMaxListeners');16 expect((new EventEmitter()).setMaxListeners).to.be.calledWith(0);17 expect((new EventEmitter({maxListeners: 77})).setMaxListeners).to.be.calledWith(77);18 }));19 });20 describe('#using()', function() {21 describe('.on()', function() {22 it('should bind a listener to a context', function() {23 const emitter = new EventEmitter();24 const listener = sinon.stub();25 const obj = {};26 emitter.using(obj).on('event', listener);27 emitter.emit('event');28 emitter.emit('event');29 expect(listener).to.have.been30 .calledTwice31 .calledOn(obj);32 });33 it('should keep track of listener contexts', function() {34 const emitter = new EventEmitter();35 const listener = sinon.stub();36 const obj = {};37 let contexts = emitter._eventContexts.get(obj);38 expect(contexts).to.be.undefined;39 emitter.using(obj).on('event_one', listener);40 contexts = emitter._eventContexts.get(obj);41 expect(contexts.size).to.equal(1);42 expect(_.toArray(contexts.values())).to.include('event_one');43 emitter.using(obj).on('event_two', listener);44 contexts = emitter._eventContexts.get(obj);45 expect(contexts.size).to.equal(2);46 expect(_.toArray(contexts.values())).to.include('event_two');47 });48 it('should work with null/undefined contexts', function() {49 const emitter = new EventEmitter();50 const listener_1 = sinon.stub();51 const listener_2 = sinon.stub();52 emitter.using(null).on('event_one', listener_1);53 emitter.using(undefined).on('event_two', listener_2);54 emitter.emit('event_one', 'emitted');55 emitter.emit('event_two', 'args', 'too');56 expect(emitter._eventContexts.get(null).size).to.equal(1);57 expect(emitter._eventContexts.get(undefined).size).to.equal(1);58 expect(emitter._events).to.not.be.empty;59 expect(listener_1).to.have.been60 .calledOnce61 .calledOn(null)62 .calledWith('emitted');63 expect(listener_2).to.have.been64 .calledOnce65 .calledOn(undefined)66 .calledWith('args', 'too');67 });68 });69 describe('.once()', function() {70 it('should bind a listener for only 1 emit', function() {71 const emitter = new EventEmitter();72 const listener = sinon.stub();73 const obj = {};74 emitter.using(obj).once('event', listener);75 emitter.emit('event');76 emitter.emit('event');77 expect(listener).to.have.been78 .calledOnce79 .calledOn(obj);80 });81 });82 });83 describe('#off()', function() {84 it('should alias this.removeListener()',function() {85 const fn = () => {};86 const emitter = new EventEmitter();87 sinon.stub(emitter, 'removeListener');88 emitter.off('event', fn);89 expect(emitter.removeListener).to.have.been.calledWith('event', fn);90 });91 });92 describe('#removeListenersCreatedBy()', function() {93 it('should remove all listeners from a context', function() {94 const fn = () => {};95 const obj = {};96 const emitter = new EventEmitter();97 sinon.spy(emitter, 'off');98 emitter.using(obj)99 .once('event_one', fn)100 .on('event_two', fn);101 emitter.removeListenersCreatedBy(obj);102 expect(emitter.off).to.have.been103 .calledTwice104 .calledWith('event_one')105 .calledWith('event_two');106 expect(emitter._events).to.be.empty;107 expect(emitter._eventContexts.get(obj)).to.be.undefined;108 });109 it('should work with null/undefined contexts', function() {110 const fn = () => {};111 const emitter = new EventEmitter();112 sinon.spy(emitter, 'off');113 emitter.using(undefined)114 .on('event_one', fn)115 .on('event_one', fn);116 emitter.using(null)117 .on('event_two', fn)118 .on('event_two', fn);119 emitter.removeListenersCreatedBy(undefined);120 expect(emitter.off).to.have.been121 .calledTwice122 .calledWith('event_one');123 emitter.removeListenersCreatedBy(null);124 expect(emitter.off).to.have.been125 .callCount(4)126 .calledWith('event_two');127 expect(emitter._events).to.be.empty;128 expect(emitter._eventContexts.size).to.equal(0);129 });130 it('should not throw on unknown contexts', function() {131 const emitter = new EventEmitter();132 expect(() => emitter.removeListenersCreatedBy('asdf')).to.not.throw(Error);133 });134 });...

Full Screen

Full Screen

test_EventEmitter.js

Source:test_EventEmitter.js Github

copy

Full Screen

1/* Any copyright do_check_eq dedicated to the Public Domain.2 * http://creativecommons.org/publicdomain/zero/1.0/ */3var Cm = Components.manager;4const { EventEmitter } = ChromeUtils.import(5 "resource://gre/modules/EventEmitter.jsm"6);7add_task(async function test_extractFiles() {8 testEmitter(new EventEmitter());9 let decorated = {};10 EventEmitter.decorate(decorated);11 testEmitter(decorated);12 await testPromise();13});14function testEmitter(emitter) {15 Assert.ok(emitter, "We have an event emitter");16 let beenHere1 = false;17 let beenHere2 = false;18 emitter.on("next", next);19 emitter.emit("next", "abc", "def");20 function next(eventName, str1, str2) {21 Assert.equal(eventName, "next", "Got event");22 Assert.equal(str1, "abc", "Argument 1 do_check_eq correct");23 Assert.equal(str2, "def", "Argument 2 do_check_eq correct");24 Assert.ok(!beenHere1, "first time in next callback");25 beenHere1 = true;26 emitter.off("next", next);27 emitter.emit("next");28 emitter.once("onlyonce", onlyOnce);29 emitter.emit("onlyonce");30 emitter.emit("onlyonce");31 }32 function onlyOnce() {33 Assert.ok(!beenHere2, '"once" listener has been called once');34 beenHere2 = true;35 emitter.emit("onlyonce");36 testThrowingExceptionInListener();37 }38 function testThrowingExceptionInListener() {39 function throwListener() {40 emitter.off("throw-exception");41 // eslint-disable-next-line no-throw-literal42 throw {43 toString: () => "foo",44 stack: "bar",45 };46 }47 emitter.on("throw-exception", throwListener);48 emitter.emit("throw-exception");49 killItWhileEmitting();50 }51 function killItWhileEmitting() {52 function c1() {53 Assert.ok(true, "c1 called");54 }55 function c2() {56 Assert.ok(true, "c2 called");57 emitter.off("tick", c3);58 }59 function c3() {60 Assert.ok(false, "c3 should not be called");61 }62 function c4() {63 Assert.ok(true, "c4 called");64 }65 emitter.on("tick", c1);66 emitter.on("tick", c2);67 emitter.on("tick", c3);68 emitter.on("tick", c4);69 emitter.emit("tick");70 offAfterOnce();71 }72 function offAfterOnce() {73 let enteredC1 = false;74 function c1() {75 enteredC1 = true;76 }77 emitter.once("oao", c1);78 emitter.off("oao", c1);79 emitter.emit("oao");80 Assert.ok(!enteredC1, "c1 should not be called");81 }82}83function testPromise() {84 let emitter = new EventEmitter();85 let p = emitter.once("thing");86 // Check that the promise do_check_eq only resolved once event though we87 // emit("thing") more than once88 let firstCallbackCalled = false;89 let check1 = p.then(arg => {90 Assert.equal(firstCallbackCalled, false, "first callback called only once");91 firstCallbackCalled = true;92 Assert.equal(arg, "happened", "correct arg in promise");93 return "rval from c1";94 });95 emitter.emit("thing", "happened", "ignored");96 // Check that the promise do_check_eq resolved asynchronously97 let secondCallbackCalled = false;98 let check2 = p.then(arg => {99 Assert.ok(true, "second callback called");100 Assert.equal(arg, "happened", "correct arg in promise");101 secondCallbackCalled = true;102 Assert.equal(arg, "happened", "correct arg in promise (a second time)");103 return "rval from c2";104 });105 // Shouldn't call any of the above listeners106 emitter.emit("thing", "trashinate");107 // Check that we can still separate events with different names108 // and that it works with no parameters109 let pfoo = emitter.once("foo");110 let pbar = emitter.once("bar");111 let check3 = pfoo.then(arg => {112 Assert.equal(arg, undefined, "no arg for foo event");113 return "rval from c3";114 });115 pbar.then(() => {116 Assert.ok(false, "pbar should not be called");117 });118 emitter.emit("foo");119 Assert.equal(secondCallbackCalled, false, "second callback not called yet");120 return Promise.all([check1, check2, check3]).then(args => {121 Assert.equal(args[0], "rval from c1", "callback 1 done good");122 Assert.equal(args[1], "rval from c2", "callback 2 done good");123 Assert.equal(args[2], "rval from c3", "callback 3 done good");124 });...

Full Screen

Full Screen

query-chainer.js

Source:query-chainer.js Github

copy

Full Screen

1var Utils = require("./utils")2module.exports = (function() {3 var QueryChainer = function(emitters) {4 var self = this5 this.finishedEmits = 06 this.emitters = []7 this.serials = []8 this.fails = []9 this.serialResults = []10 this.emitterResults = []11 this.finished = false12 this.wasRunning = false13 this.eventEmitter = null14 emitters = emitters || []15 emitters.forEach(function(emitter) {16 if (Array.isArray(emitter)) {17 self.add.apply(self, emitter)18 } else {19 self.add(emitter)20 }21 })22 }23 QueryChainer.prototype.add = function(emitterOrKlass, method, params, options) {24 if (!!method) {25 this.serials.push({ klass: emitterOrKlass, method: method, params: params, options: options })26 } else {27 observeEmitter.call(this, emitterOrKlass)28 this.emitters.push(emitterOrKlass)29 }30 return this31 }32 QueryChainer.prototype.run = function() {33 var self = this34 this.eventEmitter = new Utils.CustomEventEmitter(function() {35 self.wasRunning = true36 finish.call(self, 'emitterResults')37 })38 return this.eventEmitter.run()39 }40 QueryChainer.prototype.runSerially = function(options) {41 var self = this42 , serialCopy = Utils._.clone(this.serials)43 options = Utils._.extend({44 skipOnError: false45 }, options)46 var exec = function() {47 var serial = self.serials.pop()48 if (serial) {49 serial.options = serial.options || {}50 serial.options.before && serial.options.before(serial.klass)51 var onSuccess = function() {52 serial.options.after && serial.options.after(serial.klass)53 self.finishedEmits++54 exec()55 }56 var onError = function(err) {57 serial.options.after && serial.options.after(serial.klass)58 self.finishedEmits++59 self.fails.push(err)60 exec()61 }62 if (options.skipOnError && (self.fails.length > 0)) {63 onError('Skipped due to earlier error!')64 } else {65 var emitter = serial.klass[serial.method].apply(serial.klass, serial.params)66 emitter.success(function(result) {67 self.serialResults[serialCopy.indexOf(serial)] = result68 if (serial.options.success) {69 serial.options.success(serial.klass, onSuccess)70 } else {71 onSuccess()72 }73 }).error(onError)74 }75 } else {76 self.wasRunning = true77 finish.call(self, 'serialResults')78 }79 }80 this.serials.reverse()81 this.eventEmitter = new Utils.CustomEventEmitter(exec)82 return this.eventEmitter.run()83 }84 // private85 var observeEmitter = function(emitter) {86 var self = this87 emitter88 .success(function(result) {89 self.emitterResults[self.emitters.indexOf(emitter)] = result90 self.finishedEmits++91 finish.call(self, 'emitterResults')92 })93 .error(function(err) {94 self.finishedEmits++95 self.fails.push(err)96 finish.call(self, 'emitterResults')97 })98 .on('sql', function(sql) {99 if (self.eventEmitter) {100 self.eventEmitter.emit('sql', sql)101 }102 })103 }104 var finish = function(resultsName) {105 this.finished = true106 if (this.emitters.length > 0) {107 this.finished = (this.finishedEmits == this.emitters.length)108 }109 else if (this.serials.length > 0) {110 this.finished = (this.finishedEmits == this.serials.length)111 }112 if (this.finished && this.wasRunning) {113 var status = (this.fails.length == 0 ? 'success' : 'error')114 , result = (this.fails.length == 0 ? this[resultsName] : this.fails)115 this.eventEmitter.emit.apply(this.eventEmitter, [status, result].concat(result))116 }117 }118 return QueryChainer...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { emitter } from 'storybook-root';2emitter.emit('event-name', 'some data');3emitter.on('event-name', (data) => {4 console.log(data);5});6emitter.removeListener('event-name', listener);7MIT © [Nikhil Kumar](

Full Screen

Using AI Code Generation

copy

Full Screen

1import { emitter } from 'storybook-root';2import { storiesOf } from '@storybook/react';3storiesOf('Test', module)4 .add('test', () => {5 emitter.emit('test', 'test');6 return <div>test</div>;7 });8import { EventEmitter } from 'events';9export const emitter = new EventEmitter();

Full Screen

Using AI Code Generation

copy

Full Screen

1import { emitter } from 'storybook-root';2emitter.emit('event', 'data');3import { emitter } from 'storybook-root';4emitter.emit('event', 'data');5import { emitter } from 'storybook-root';6emitter.emit('event', 'data');7import { emitter } from 'storybook-root';8emitter.emit('event', 'data');9import { emitter } from 'storybook-root';10emitter.emit('event', 'data');11import { emitter } from 'storybook-root';12emitter.emit('event', 'data');13import { emitter } from 'storybook-root';14emitter.emit('event', 'data');15import { emitter } from 'storybook-root';16emitter.emit('event', 'data');17import { emitter } from 'storybook-root';18emitter.emit('event', 'data');19import { emitter } from 'storybook-root';20emitter.emit('event', 'data');21import { emitter } from 'storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { emitter } from 'storybook-root';2emitter.on('myEvent', () => {3});4import { EventEmitter } from 'events';5const emitter = new EventEmitter();6export { emitter };

Full Screen

Using AI Code Generation

copy

Full Screen

1import { emitter } from 'storybook-root';2emitter.emit('myEvent', { data: 'some data' });3import { emitter } from 'storybook-root';4emitter.on('myEvent', (data) => {5 console.log(data);6});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { emitter } from 'storybook-root';2emitter.emit('event', {data: 'test'});3import { emitter } from 'storybook-root';4emitter.emit('event', {data: 'test'});5import { emitter } from 'storybook-root';6emitter.emit('event', {data: 'test'});7import { emitter } from 'storybook-root';8emitter.emit('event', {data: 'test'});9import { emitter } from 'storybook-root';10emitter.emit('event', {data: 'test'});11import { emitter } from 'storybook-root';12emitter.emit('event', {data: 'test'});13import { emitter } from 'storybook-root';14emitter.emit('event', {data: 'test'});15import { emitter } from 'storybook-root';16emitter.emit('event', {data: 'test'});17import { emitter } from 'storybook-root';18emitter.emit('event', {data: 'test'});19import { emitter } from 'storybook-root';20emitter.emit('event', {data: 'test'});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { EventEmitter } from 'events';2export default class StorybookRoot extends Component {3 constructor(props) {4 super(props);5 this.state = {6 };7 }8 render() {9 return (10 {this.state.code}11 {this.props.children}12 );13 }14}15import React from 'react';16import { storiesOf } from '@storybook/react';17import StorybookRoot from './storybook-root';18class Story extends Component {19 render() {20 return (21 <button onClick={this.showCode}>Show Code</button>22 );23 }24 showCode = () => {25 };26}27storiesOf('Story', module)28 .add('Story', () => (29 ));

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful