Best JavaScript code snippet using wpt
CCEventListener.js
Source:CCEventListener.js
1/****************************************************************************2 Copyright (c) 2011-2012 cocos2d-x.org3 Copyright (c) 2013-2014 Chukong Technologies Inc.4 http://www.cocos2d-x.org5 Permission is hereby granted, free of charge, to any person obtaining a copy6 of this software and associated documentation files (the "Software"), to deal7 in the Software without restriction, including without limitation the rights8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9 copies of the Software, and to permit persons to whom the Software is10 furnished to do so, subject to the following conditions:11 The above copyright notice and this permission notice shall be included in12 all copies or substantial portions of the Software.13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19 THE SOFTWARE.20 ****************************************************************************/21/**22 * <p>23 * The base class of event listener. <br/>24 * If you need custom listener which with different callback, you need to inherit this class. <br/>25 * For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard, <br/>26 * EventListenerTouchOneByOne, EventListenerCustom.27 * </p>28 * @class29 * @extends cc.Class30 */31cc.EventListener = cc.Class.extend(/** @lends cc.EventListener# */{32 _onEvent: null, // Event callback function33 _type: 0, // Event listener type34 _listenerID: null, // Event listener ID35 _registered: false, // Whether the listener has been added to dispatcher.36 _fixedPriority: 0, // The higher the number, the higher the priority, 0 is for scene graph base priority.37 _node: null, // scene graph based priority38 _paused: true, // Whether the listener is paused39 _isEnabled: true, // Whether the listener is enabled40 /**41 * Initializes event with type and callback function42 * @param {number} type43 * @param {string} listenerID44 * @param {function} callback45 */46 ctor: function (type, listenerID, callback) {47 this._onEvent = callback;48 this._type = type || 0;49 this._listenerID = listenerID || "";50 },51 /**52 * <p>53 * Sets paused state for the listener54 * The paused state is only used for scene graph priority listeners.55 * `EventDispatcher::resumeAllEventListenersForTarget(node)` will set the paused state to `true`,56 * while `EventDispatcher::pauseAllEventListenersForTarget(node)` will set it to `false`.57 * @note 1) Fixed priority listeners will never get paused. If a fixed priority doesn't want to receive events,58 * call `setEnabled(false)` instead.59 * 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners which associated with that node will be automatically updated.60 * </p>61 * @param {boolean} paused62 * @private63 */64 _setPaused: function (paused) {65 this._paused = paused;66 },67 /**68 * Checks whether the listener is paused69 * @returns {boolean}70 * @private71 */72 _isPaused: function () {73 return this._paused;74 },75 /**76 * Marks the listener was registered by EventDispatcher77 * @param {boolean} registered78 * @private79 */80 _setRegistered: function (registered) {81 this._registered = registered;82 },83 /**84 * Checks whether the listener was registered by EventDispatcher85 * @returns {boolean}86 * @private87 */88 _isRegistered: function () {89 return this._registered;90 },91 /**92 * Gets the type of this listener93 * @note It's different from `EventType`, e.g. TouchEvent has two kinds of event listeners - EventListenerOneByOne, EventListenerAllAtOnce94 * @returns {number}95 * @private96 */97 _getType: function () {98 return this._type;99 },100 /**101 * Gets the listener ID of this listener102 * When event is being dispatched, listener ID is used as key for searching listeners according to event type.103 * @returns {string}104 * @private105 */106 _getListenerID: function () {107 return this._listenerID;108 },109 /**110 * Sets the fixed priority for this listener111 * @note This method is only used for `fixed priority listeners`, it needs to access a non-zero value. 0 is reserved for scene graph priority listeners112 * @param {number} fixedPriority113 * @private114 */115 _setFixedPriority: function (fixedPriority) {116 this._fixedPriority = fixedPriority;117 },118 /**119 * Gets the fixed priority of this listener120 * @returns {number} 0 if it's a scene graph priority listener, non-zero for fixed priority listener121 * @private122 */123 _getFixedPriority: function () {124 return this._fixedPriority;125 },126 /**127 * Sets scene graph priority for this listener128 * @param {cc.Node} node129 * @private130 */131 _setSceneGraphPriority: function (node) {132 this._node = node;133 },134 /**135 * Gets scene graph priority of this listener136 * @returns {cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener137 * @private138 */139 _getSceneGraphPriority: function () {140 return this._node;141 },142 /**143 * Checks whether the listener is available.144 * @returns {boolean}145 */146 checkAvailable: function () {147 return this._onEvent != null;148 },149 /**150 * Clones the listener, its subclasses have to override this method.151 * @returns {cc.EventListener}152 */153 clone: function () {154 return null;155 },156 /**157 * Enables or disables the listener158 * @note Only listeners with `enabled` state will be able to receive events.159 * When an listener was initialized, it's enabled by default.160 * An event listener can receive events when it is enabled and is not paused.161 * paused state is always false when it is a fixed priority listener.162 * @param {boolean} enabled163 */164 setEnabled: function(enabled){165 this._isEnabled = enabled;166 },167 /**168 * Checks whether the listener is enabled169 * @returns {boolean}170 */171 isEnabled: function(){172 return this._isEnabled;173 },174 /**175 * <p>Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,176 * and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.177 * This is a hack, and should be removed once JSB fixes the retain/release bug<br/>178 * You will need to retain an object if you created a listener and haven't added it any target node during the same frame.<br/>179 * Otherwise, JSB's native autorelease pool will consider this object a useless one and release it directly,<br/>180 * when you want to use it later, a "Invalid Native Object" error will be raised.<br/>181 * The retain function can increase a reference count for the native object to avoid it being released,<br/>182 * you need to manually invoke release function when you think this object is no longer needed, otherwise, there will be memory learks.<br/>183 * retain and release function call should be paired in developer's game code.</p>184 * @function185 * @see cc.EventListener#release186 */187 retain:function () {188 },189 /**190 * <p>Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,191 * and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.192 * This is a hack, and should be removed once JSB fixes the retain/release bug<br/>193 * You will need to retain an object if you created a listener and haven't added it any target node during the same frame.<br/>194 * Otherwise, JSB's native autorelease pool will consider this object a useless one and release it directly,<br/>195 * when you want to use it later, a "Invalid Native Object" error will be raised.<br/>196 * The retain function can increase a reference count for the native object to avoid it being released,<br/>197 * you need to manually invoke release function when you think this object is no longer needed, otherwise, there will be memory learks.<br/>198 * retain and release function call should be paired in developer's game code.</p>199 * @function200 * @see cc.EventListener#retain201 */202 release:function () {203 }204});205// event listener type206/**207 * The type code of unknown event listener.208 * @constant209 * @type {number}210 */211cc.EventListener.UNKNOWN = 0;212/**213 * The type code of one by one touch event listener.214 * @constant215 * @type {number}216 */217cc.EventListener.TOUCH_ONE_BY_ONE = 1;218/**219 * The type code of all at once touch event listener.220 * @constant221 * @type {number}222 */223cc.EventListener.TOUCH_ALL_AT_ONCE = 2;224/**225 * The type code of keyboard event listener.226 * @constant227 * @type {number}228 */229cc.EventListener.KEYBOARD = 3;230/**231 * The type code of mouse event listener.232 * @constant233 * @type {number}234 */235cc.EventListener.MOUSE = 4;236/**237 * The type code of acceleration event listener.238 * @constant239 * @type {number}240 */241cc.EventListener.ACCELERATION = 5;242/**243 * The type code of custom event listener.244 * @constant245 * @type {number}246 */247cc.EventListener.CUSTOM = 6;248cc._EventListenerCustom = cc.EventListener.extend({249 _onCustomEvent: null,250 ctor: function (listenerId, callback) {251 this._onCustomEvent = callback;252 var selfPointer = this;253 var listener = function (event) {254 if (selfPointer._onCustomEvent != null)255 selfPointer._onCustomEvent(event);256 };257 cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, listener);258 },259 checkAvailable: function () {260 return (cc.EventListener.prototype.checkAvailable.call(this) && this._onCustomEvent != null);261 },262 clone: function () {263 return new cc._EventListenerCustom(this._listenerID, this._onCustomEvent);264 }265});266cc._EventListenerCustom.create = function (eventName, callback) {267 return new cc._EventListenerCustom(eventName, callback);268};269cc._EventListenerMouse = cc.EventListener.extend({270 onMouseDown: null,271 onMouseUp: null,272 onMouseMove: null,273 onMouseScroll: null,274 ctor: function () {275 var selfPointer = this;276 var listener = function (event) {277 var eventType = cc.EventMouse;278 switch (event._eventType) {279 case eventType.DOWN:280 if (selfPointer.onMouseDown)281 selfPointer.onMouseDown(event);282 break;283 case eventType.UP:284 if (selfPointer.onMouseUp)285 selfPointer.onMouseUp(event);286 break;287 case eventType.MOVE:288 if (selfPointer.onMouseMove)289 selfPointer.onMouseMove(event);290 break;291 case eventType.SCROLL:292 if (selfPointer.onMouseScroll)293 selfPointer.onMouseScroll(event);294 break;295 default:296 break;297 }298 };299 cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, listener);300 },301 clone: function () {302 var eventListener = new cc._EventListenerMouse();303 eventListener.onMouseDown = this.onMouseDown;304 eventListener.onMouseUp = this.onMouseUp;305 eventListener.onMouseMove = this.onMouseMove;306 eventListener.onMouseScroll = this.onMouseScroll;307 return eventListener;308 },309 checkAvailable: function () {310 return true;311 }312});313cc._EventListenerMouse.LISTENER_ID = "__cc_mouse";314cc._EventListenerMouse.create = function () {315 return new cc._EventListenerMouse();316};317cc._EventListenerTouchOneByOne = cc.EventListener.extend({318 _claimedTouches: null,319 swallowTouches: false,320 onTouchBegan: null,321 onTouchMoved: null,322 onTouchEnded: null,323 onTouchCancelled: null,324 ctor: function () {325 cc.EventListener.prototype.ctor.call(this, cc.EventListener.TOUCH_ONE_BY_ONE, cc._EventListenerTouchOneByOne.LISTENER_ID, null);326 this._claimedTouches = [];327 },328 setSwallowTouches: function (needSwallow) {329 this.swallowTouches = needSwallow;330 },331 clone: function () {332 var eventListener = new cc._EventListenerTouchOneByOne();333 eventListener.onTouchBegan = this.onTouchBegan;334 eventListener.onTouchMoved = this.onTouchMoved;335 eventListener.onTouchEnded = this.onTouchEnded;336 eventListener.onTouchCancelled = this.onTouchCancelled;337 eventListener.swallowTouches = this.swallowTouches;338 return eventListener;339 },340 checkAvailable: function () {341 if(!this.onTouchBegan){342 cc.log(cc._LogInfos._EventListenerTouchOneByOne_checkAvailable);343 return false;344 }345 return true;346 }347});348cc._EventListenerTouchOneByOne.LISTENER_ID = "__cc_touch_one_by_one";349cc._EventListenerTouchOneByOne.create = function () {350 return new cc._EventListenerTouchOneByOne();351};352cc._EventListenerTouchAllAtOnce = cc.EventListener.extend({353 onTouchesBegan: null,354 onTouchesMoved: null,355 onTouchesEnded: null,356 onTouchesCancelled: null,357 ctor: function(){358 cc.EventListener.prototype.ctor.call(this, cc.EventListener.TOUCH_ALL_AT_ONCE, cc._EventListenerTouchAllAtOnce.LISTENER_ID, null);359 },360 clone: function(){361 var eventListener = new cc._EventListenerTouchAllAtOnce();362 eventListener.onTouchesBegan = this.onTouchesBegan;363 eventListener.onTouchesMoved = this.onTouchesMoved;364 eventListener.onTouchesEnded = this.onTouchesEnded;365 eventListener.onTouchesCancelled = this.onTouchesCancelled;366 return eventListener;367 },368 checkAvailable: function(){369 if (this.onTouchesBegan == null && this.onTouchesMoved == null370 && this.onTouchesEnded == null && this.onTouchesCancelled == null) {371 cc.log(cc._LogInfos._EventListenerTouchAllAtOnce_checkAvailable);372 return false;373 }374 return true;375 }376});377cc._EventListenerTouchAllAtOnce.LISTENER_ID = "__cc_touch_all_at_once";378cc._EventListenerTouchAllAtOnce.create = function(){379 return new cc._EventListenerTouchAllAtOnce();380};381/**382 * Create a EventListener object by json object383 * @function384 * @static385 * @param {object} argObj a json object386 * @returns {cc.EventListener}387 * todo: It should be the direct use new388 * @example389 * cc.EventListener.create({390 * event: cc.EventListener.TOUCH_ONE_BY_ONE,391 * swallowTouches: true,392 * onTouchBegan: function (touch, event) {393 * //do something394 * return true;395 * }396 * });397 */398cc.EventListener.create = function(argObj){399 cc.assert(argObj&&argObj.event, cc._LogInfos.EventListener_create);400 var listenerType = argObj.event;401 delete argObj.event;402 var listener = null;403 if(listenerType === cc.EventListener.TOUCH_ONE_BY_ONE)404 listener = new cc._EventListenerTouchOneByOne();405 else if(listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE)406 listener = new cc._EventListenerTouchAllAtOnce();407 else if(listenerType === cc.EventListener.MOUSE)408 listener = new cc._EventListenerMouse();409 else if(listenerType === cc.EventListener.CUSTOM){410 listener = new cc._EventListenerCustom(argObj.eventName, argObj.callback);411 delete argObj.eventName;412 delete argObj.callback;413 } else if(listenerType === cc.EventListener.KEYBOARD)414 listener = new cc._EventListenerKeyboard();415 else if(listenerType === cc.EventListener.ACCELERATION){416 listener = new cc._EventListenerAcceleration(argObj.callback);417 delete argObj.callback;418 }419 for(var key in argObj) {420 listener[key] = argObj[key];421 }422 return listener;...
event-listener.js
Source:event-listener.js
1'use strict';2const assert = require('assert').strict;3const {4 EventListener,5 EventListenerError6} = require('../lib');7describe('Event Listener', () => {8 const sampleEvent = {9 service: 'id',10 client: 'fizzmod',11 entity: 'profile',12 id: '5d699c1ae8ebb95eaa24aca9',13 event: 'created'14 };15 describe('Getters', () => {16 it('Should return false as mustHaveClient and mustHaveId getters default', () => {17 const eventListener = new EventListener();18 assert.strictEqual(eventListener.mustHaveClient, false);19 assert.strictEqual(eventListener.mustHaveId, false);20 });21 it('Should return an empty event and undefined event details if data is empty', () => {22 const eventListener = new EventListener();23 eventListener.data = {};24 assert.deepStrictEqual(eventListener.event, {});25 assert.strictEqual(eventListener.eventService, undefined);26 assert.strictEqual(eventListener.eventEntity, undefined);27 assert.strictEqual(eventListener.eventName, undefined);28 assert.strictEqual(eventListener.eventClient, undefined);29 assert.strictEqual(eventListener.eventId, undefined);30 });31 it('Should return each event details if data is set', () => {32 const eventListener = new EventListener();33 eventListener.data = { ...sampleEvent };34 assert.deepStrictEqual(eventListener.event, { ...sampleEvent });35 assert.strictEqual(eventListener.eventService, 'id');36 assert.strictEqual(eventListener.eventEntity, 'profile');37 assert.strictEqual(eventListener.eventName, 'created');38 assert.strictEqual(eventListener.eventClient, 'fizzmod');39 assert.strictEqual(eventListener.eventId, '5d699c1ae8ebb95eaa24aca9');40 });41 it('Should return false as shouldCreateLog getter', () => {42 const eventListener = new EventListener();43 assert.strictEqual(eventListener.shouldCreateLog, false);44 });45 });46 describe('Validation', () => {47 it('Should reject if data is not set', async () => {48 const eventListener = new EventListener();49 await assert.rejects(() => eventListener.validate(), {50 code: EventListenerError.codes.MISSING_EVENT51 });52 });53 it('Should reject if data is not an object', async () => {54 const eventListener = new EventListener();55 eventListener.data = 'hi';56 await assert.rejects(() => eventListener.validate(), {57 code: EventListenerError.codes.INVALID_EVENT58 });59 eventListener.data = [];60 await assert.rejects(() => eventListener.validate(), {61 code: EventListenerError.codes.INVALID_EVENT62 });63 });64 it('Should reject if service property is missing', async () => {65 const { service, ...event } = { ...sampleEvent };66 const eventListener = new EventListener();67 eventListener.data = event;68 await assert.rejects(() => eventListener.validate(), {69 code: EventListenerError.codes.INVALID_EVENT70 });71 });72 it('Should reject if service property is not a string', async () => {73 const { service, ...event } = { ...sampleEvent };74 const eventListener = new EventListener();75 eventListener.data = {76 ...event,77 service: ['invalid']78 };79 await assert.rejects(() => eventListener.validate(), {80 code: EventListenerError.codes.INVALID_EVENT81 });82 });83 it('Should reject if entity property is missing', async () => {84 const { entity, ...event } = { ...sampleEvent };85 const eventListener = new EventListener();86 eventListener.data = event;87 await assert.rejects(() => eventListener.validate(), {88 code: EventListenerError.codes.INVALID_EVENT89 });90 });91 it('Should reject if entity property is not a string', async () => {92 const { entity, ...event } = { ...sampleEvent };93 const eventListener = new EventListener();94 eventListener.data = {95 ...event,96 entity: ['invalid']97 };98 await assert.rejects(() => eventListener.validate(), {99 code: EventListenerError.codes.INVALID_EVENT100 });101 });102 it('Should reject if event property is missing', async () => {103 const { event: eventName, ...event } = { ...sampleEvent };104 const eventListener = new EventListener();105 eventListener.data = event;106 await assert.rejects(() => eventListener.validate(), {107 code: EventListenerError.codes.INVALID_EVENT108 });109 });110 it('Should reject if event property is not a string', async () => {111 const { event: eventName, ...event } = { ...sampleEvent };112 const eventListener = new EventListener();113 eventListener.data = {114 ...event,115 event: ['invalid']116 };117 await assert.rejects(() => eventListener.validate(), {118 code: EventListenerError.codes.INVALID_EVENT119 });120 });121 it('Should reject if client property is not a string', async () => {122 const { client, ...event } = { ...sampleEvent };123 const eventListener = new EventListener();124 eventListener.data = {125 ...event,126 client: ['invalid']127 };128 await assert.rejects(() => eventListener.validate(), {129 code: EventListenerError.codes.INVALID_EVENT130 });131 });132 it('Should reject if id property is not a string or a number', async () => {133 const { id, ...event } = { ...sampleEvent };134 const eventListener = new EventListener();135 eventListener.data = {136 ...event,137 id: ['invalid']138 };139 await assert.rejects(() => eventListener.validate(), {140 code: EventListenerError.codes.INVALID_EVENT141 });142 });143 class MyEventListener extends EventListener {144 get mustHaveClient() {145 return true;146 }147 get mustHaveId() {148 return true;149 }150 }151 it('Should reject if client property is missing and Listener mustHaveClient', async () => {152 const { client, ...event } = { ...sampleEvent };153 const eventListener = new MyEventListener();154 eventListener.data = {155 ...event156 };157 await assert.rejects(() => eventListener.validate(), {158 code: EventListenerError.codes.INVALID_EVENT159 });160 });161 it('Should reject if id property is missing and Listener mustHaveId', async () => {162 const { id, ...event } = { ...sampleEvent };163 const eventListener = new MyEventListener();164 eventListener.data = {165 ...event166 };167 await assert.rejects(() => eventListener.validate(), {168 code: EventListenerError.codes.INVALID_EVENT169 });170 });171 it('Should pass validation for minimum valid event', async () => {172 const { client, id, ...event } = { ...sampleEvent };173 const eventListener = new EventListener();174 eventListener.data = {175 ...event176 };177 await assert.doesNotReject(() => eventListener.validate());178 });179 it('Should pass validation for full valid event if Listener mustHaveClient and mustHaveId', async () => {180 const eventListener = new MyEventListener();181 eventListener.data = { ...sampleEvent };182 await assert.doesNotReject(() => eventListener.validate());183 });184 });...
eventHandlers.js
Source:eventHandlers.js
1/*2 * Make an eventListener class with .trigger(), .off(), and .on() methods.3 *4 * Example:5 *6 * const eventListener = new EventListener();7 *8 * eventListener.on('click', function() {9 * console.log('clicked');10 * });11 *12 * eventListener.trigger('click');13 * --> Calling this logs: 'clicked'14 *15 * Requirements:16 * - It should be able to handle multiple callback functions for the same event name.17 * - If eventListener.trigger is called with additional arguments it should pass those to the listeners.18 * - We should be able to remove a given event listener.19 *20 * ----------------------------------------------------21 * Example 1:22 *23 * const eventListener = new EventListener();24 *25 * eventListener.on('click', function() {26 * console.log('clicked');27 * });28 *29 * eventListener.trigger('click');30 *31 * --> logs: 'clicked'32 *33 * ----------------------------------------------------34 * Example 2:35 *36 * const eventListener = new EventListener();37 *38 * eventListener.on('click', function() {39 * console.log('clicked');40 * });41 *42 * eventListener.on('click', function() {43 * console.log('clicked again');44 * });45 *46 * eventListener.off('click', )47 *48 * eventListener.trigger('click');49 *50 * --> logs: 'clicked'51 * 'clicked again'52 *53 * ----------------------------------------------------54 * Example 3:55 *56 * const eventListener = new EventListener();57 *58 * function logClicked() {59 * console.log('clicked');60 * }61 *62 * eventListener.on('click', logClicked);63 *64 * eventListener.trigger('click');65 *66 * --> logs: 'clicked'67 *68 * eventListener.off('click', logClicked);69 *70 * eventListener.trigger('click');71 *72 * --> does nothing.73 *74 * ----------------------------------------------------75 * Example 4:76 *77 * const eventListener = new EventListener();78 *79 * eventListener.on('abc', function(target) {80 * console.log('clicked: ' + target);81 * });82 *83 * eventListener.trigger('abc', 'button');84 *85 * --> logs: 'clicked: button'86 *87 *88 * EventListener class89 * .on() method, .off() method, .trigger() method90 *91 * .on()92 * takes an event name, and callback as arguments93 * store the event name and its callback in an object94 * .on(eventName, callback) {95 * object[eventName] = [callback];96 * }97 *98 * {'click': [callback1, callback2]}99 *100 * .trigger('click', arg1, arg2)101 * Invoke all of the callbacks specified in calls to .on() that match the event name102 * If it's passed an additional argument, it should pass that as the arg to the callbacks in .on()103 * [callback1, callback2]104 * Iterate over the callbacks returned, invoke each callback105 * arguments = ['click', arg1, arg2]106 * .trigger(eventName, ...args) {107 * const callbacks = events[eventName];108 * Iterate over callbacks, callback(args)109 * }110 *111 * .off(eventName, function)112 * Lookup the eventhandler callbacks113 * if function is undefined, return114 * iterate over the callbacks and compare to input function115 * if one matches, splice it out of the callback array116 * if after splicing the callback arry is lenth 0, delete the property117 *118 * /119 * */120class EventListener {121 constructor() {122 this.eventHandlers = {};123 }124 on = (eventName, callback) => {125 if (this.eventHandlers[eventName]) {126 this.eventHandlers[eventName].push(callback);127 } else {128 this.eventHandlers[eventName] = [callback];129 }130 }131 trigger = (eventName, ...args) => {132 const callbacks = this.eventHandlers[eventName];133 if (!callbacks) {134 console.log('Event removed');135 return;136 }137 callbacks.forEach(cb => {138 cb.apply(this, args);139 });140 }141 off = (eventName, callback) => {142 if (!callback) {143 return;144 }145 const callbacks = this.eventHandlers[eventName];146 callbacks.forEach((cb, i) => {147 if (cb === callback) {148 callbacks.splice(i, 1);149 }150 });151 if (callbacks.length === 0) {152 delete this.eventHandlers[eventName];153 }154 }155}156// const eventListener = new EventListener();157// eventListener.on('click', function() {158// console.log('clicked');159// });160// eventListener.trigger('click');161// --> logs: 'clicked'162 // const eventListener = new EventListener();163 // function logClicked() {164 // console.log('clicked');165 // }166 // eventListener.on('click', logClicked);167 // eventListener.trigger('click');168 // // --> logs: 'clicked'169 // eventListener.off('click', logClicked);170 // eventListener.trigger('click');171// --> logs: 'clicked: button'172 const eventListener = new EventListener();173 eventListener.on('click', function() {174 console.log('clicked');175 });176 eventListener.on('click', function() {177 console.log('clicked again');178 });179 eventListener.off('click', )...
Using AI Code Generation
1addEventListener('fetch', event => {2 event.respondWith(handleRequest(event.request))3})4 * @param {Request} request5async function handleRequest(request) {6 console.log(request)7 return new Response('Hello worker!', {8 headers: { 'content-type': 'text/plain' }9 })10}11addEventListener('fetch', event => {12 event.respondWith(handleRequest(event.request))13})14 * @param {Request} request15async function handleRequest(request) {16 console.log(request)17 return new Response('Hello worker!', {18 headers: { 'content-type': 'text/plain' }19 })20}21addEventListener('fetch', event => {22 event.respondWith(handleRequest(event.request))23})24 * @param {Request} request25async function handleRequest(request) {26 console.log(request)27 return new Response('Hello worker!', {28 headers: { 'content-type': 'text/plain' }29 })30}31addEventListener('fetch', event => {32 event.respondWith(handleRequest(event.request))33})34 * @param {Request} request35async function handleRequest(request) {36 console.log(request)37 return new Response('Hello worker!', {38 headers: { 'content-type': 'text/plain' }39 })40}41addEventListener('fetch', event => {42 event.respondWith(handleRequest(event.request))43})44 * @param {Request} request45async function handleRequest(request) {46 console.log(request)47 return new Response('Hello worker!', {48 headers: { 'content-type': 'text/plain' }49 })50}51addEventListener('fetch', event => {52 event.respondWith(handleRequest(event.request))53})54 * @param {Request} request55async function handleRequest(request) {56 console.log(request)
Using AI Code Generation
1addEventListener("fetch", event => {2 event.respondWith(handleRequest(event.request));3});4 * @param {Request} request5async function handleRequest(request) {6 let response = await fetch(request);7 return response;8}9addEventListener("fetch", event => {10 event.respondWith(handleRequest(event.request));11});12 * @param {Request} request13async function handleRequest(request) {14 let response = await fetch(request);15 return response;16}17addEventListener("fetch", event => {18 event.respondWith(handleRequest(event.request));19});20 * @param {Request} request21async function handleRequest(request) {22 let response = await fetch(request);23 return response;24}25addEventListener("fetch", event => {26 event.respondWith(handleRequest(event.request));27});28 * @param {Request} request29async function handleRequest(request) {30 let response = await fetch(request);31 return response;32}33addEventListener("fetch", event => {34 event.respondWith(handleRequest(event.request));35});36 * @param {Request} request37async function handleRequest(request) {38 let response = await fetch(request);
Using AI Code Generation
1var wptools = require('wptools');2var wiki = wptools.page('Barack_Obama');3wiki.get(function(err, resp) {4 if (err) {5 console.log(err);6 }7 else {8 console.log(resp);9 }10});11var wptools = require('wptools');12var wiki = wptools.page('Barack_Obama');13wiki.on('info', function(info) {14 console.log(info);15});16wiki.get();17var wptools = require('wptools');18var wiki = wptools.page('Barack_Obama');19wiki.get(function(err, resp) {20 if (err) {21 console.log(err);22 }23 else {24 console.log(resp);25 }26});27var wptools = require('wptools');28var wiki = wptools.page('Barack_Obama');29wiki.get()30 .then(function(resp) {31 console.log(resp);32 })33 .catch(function(err) {34 console.log(err);35 });36var wptools = require('wptools');37var wiki = wptools.page('Barack_Obama');38wiki.get(function(err, resp) {39 if (err) {40 console.log(err);41 }42 else {43 console.log(resp);44 }45});46var wptools = require('wptools');47var wiki = wptools.page('Barack_Obama');48wiki.get()49 .then(function(resp) {50 console.log(resp);51 })52 .catch(function(err) {53 console.log(err);54 });55var wptools = require('wptools');56var wiki = wptools.page('Barack_Obama');57wiki.get(function(err, resp) {58 if (err) {59 console.log(err);60 }61 else {62 console.log(resp);63 }64});65var wptools = require('wptools');66var wiki = wptools.page('Barack_Obama');67wiki.get()68 .then(function(resp) {
Using AI Code Generation
1window.addEventListener("load", function(){2});3window.onload = function(){4};5$(document).ready(function(){6});7$(function(){8});9$(document).on("ready", function(){10});11$(document).on("load", function(){12});13$(document).on("DOMContentLoaded", function(){14});15window.addEventListener("DOMContentLoaded", function(){16});
Using AI Code Generation
1addEventListener('fetch', event => {2 event.respondWith(handleRequest(event.request))3})4async function handleRequest(request) {5 const url = new URL(request.url)6 const cookie = new Headers()7 cookie.set('name', 'value')8 cookie.set('name1', 'value1')9 const response = new Response('ok', {10 headers: {11 },12 })13}14addEventListener('fetch', event => {15 event.respondWith(handleRequest(event.request))16})17async function handleRequest(request) {18 const url = new URL(request.url)19 const cookie = new Headers()20 cookie.set('name', 'value')21 cookie.set('name1', 'value1')22 const response = new Response('ok', {23 headers: {24 },25 })26}27addEventListener('fetch', event => {28 event.respondWith(handleRequest(event.request))29})30async function handleRequest(request) {31 const url = new URL(request.url)32 const cookie = new Headers()33 cookie.set('name', 'value')34 cookie.set('name1', 'value1')35 const response = new Response('ok', {36 headers: {37 },
Using AI Code Generation
1window.addEventListener('load', function () {2 document.getElementById('test').addEventListener('click', function () {3 console.log('clicked');4 });5});6window.addEventListener('load', function () {7 document.getElementById('test').addEventListener('click', function () {8 console.log('clicked');9 });10});11window.addEventListener('load', function () {12 document.getElementById('test').addEventListener('click', function () {13 console.log('clicked');14 });15});16window.addEventListener('load', function () {17 document.getElementById('test').addEventListener('click', function () {18 console.log('clicked');19 });20});
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('<your api key>');3wpt.runTest('<url>', function(err, data) {4 if (err) return console.log(err);5 console.log(data);6 var testId = data.data.testId;7 wpt.getTestResults(testId, function(err, data) {8 if (err) return console.log(err);9 console.log(data);10 });11});12var wpt = require('wpt');13var wpt = new WebPageTest('<your api key>');14wpt.runTest('<url>')15 .then(data => {16 console.log(data);17 var testId = data.data.testId;18 return wpt.getTestResults(testId);19 })20 .then(data => {21 console.log(data);22 })23 .catch(err => {24 console.log(err);25 });
Using AI Code Generation
1window.addEventListener('wptouchready', function() {2 console.log('wptouchready event triggered');3}, false);4jQuery(document).on('wptouchready', function() {5 console.log('wptouchready event triggered');6});7jQuery(document).ready(function() {8 console.log('wptouchready event triggered');9});10jQuery(window).load(function() {11 console.log('wptouchready event triggered');12});13jQuery(document).ready(function() {14 console.log('wptouchready event triggered');15});16jQuery(window).load(function() {17 console.log('wptouchready event triggered');18});19jQuery(document).ready(function() {20 console.log('wptouchready event triggered');21});22jQuery(window).load(function() {23 console.log('wptouchready event triggered');24});25jQuery(document).ready(function() {26 console.log('wptouchready event triggered');27});28jQuery(window).load(function()
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!