Best JavaScript code snippet using ghostjs
swipeSpec.js
Source:swipeSpec.js
1'use strict';2describe('$swipe', function() {3 var element;4 var events;5 beforeEach(function() {6 module('ngTouch');7 inject(function($compile, $rootScope) {8 element = $compile('<div></div>')($rootScope);9 });10 events = {11 start: jasmine.createSpy('startSpy'),12 move: jasmine.createSpy('moveSpy'),13 cancel: jasmine.createSpy('cancelSpy'),14 end: jasmine.createSpy('endSpy')15 };16 });17 afterEach(function() {18 dealoc(element);19 });20 describe('pointerTypes', function() {21 var usedEvents;22 var MOUSE_EVENTS = ['mousedown','mousemove','mouseup'].sort();23 var TOUCH_EVENTS = ['touchcancel','touchend','touchmove','touchstart'].sort();24 var ALL_EVENTS = MOUSE_EVENTS.concat(TOUCH_EVENTS).sort();25 beforeEach(function() {26 usedEvents = [];27 spyOn(element, 'on').andCallFake(function(events) {28 angular.forEach(events.split(/\s+/), function(eventName) {29 usedEvents.push(eventName);30 });31 });32 });33 it('should use mouse and touch by default', inject(function($swipe) {34 $swipe.bind(element, events);35 expect(usedEvents.sort()).toEqual(ALL_EVENTS);36 }));37 it('should only use mouse events for pointerType "mouse"', inject(function($swipe) {38 $swipe.bind(element, events, ['mouse']);39 expect(usedEvents.sort()).toEqual(MOUSE_EVENTS);40 }));41 it('should only use touch events for pointerType "touch"', inject(function($swipe) {42 $swipe.bind(element, events, ['touch']);43 expect(usedEvents.sort()).toEqual(TOUCH_EVENTS);44 }));45 it('should use mouse and touch if both are specified', inject(function($swipe) {46 $swipe.bind(element, events, ['touch', 'mouse']);47 expect(usedEvents.sort()).toEqual(ALL_EVENTS);48 }));49 });50 swipeTests('touch', /* restrictBrowers */ true, 'touchstart', 'touchmove', 'touchend');51 swipeTests('mouse', /* restrictBrowers */ false, 'mousedown', 'mousemove', 'mouseup');52 // Wrapper to abstract over using touch events or mouse events.53 function swipeTests(description, restrictBrowsers, startEvent, moveEvent, endEvent) {54 describe('$swipe with ' + description + ' events', function() {55 if (restrictBrowsers) {56 // TODO(braden): Once we have other touch-friendly browsers on CI, allow them here.57 // Currently Firefox and IE refuse to fire touch events.58 var chrome = /chrome/.test(navigator.userAgent.toLowerCase());59 if (!chrome) {60 return;61 }62 }63 it('should trigger the "start" event', inject(function($swipe) {64 $swipe.bind(element, events);65 expect(events.start).not.toHaveBeenCalled();66 expect(events.move).not.toHaveBeenCalled();67 expect(events.cancel).not.toHaveBeenCalled();68 expect(events.end).not.toHaveBeenCalled();69 browserTrigger(element, startEvent,{70 keys: [],71 x: 100,72 y: 2073 });74 expect(events.start).toHaveBeenCalled();75 expect(events.move).not.toHaveBeenCalled();76 expect(events.cancel).not.toHaveBeenCalled();77 expect(events.end).not.toHaveBeenCalled();78 }));79 it('should trigger the "move" event after a "start"', inject(function($swipe) {80 $swipe.bind(element, events);81 expect(events.start).not.toHaveBeenCalled();82 expect(events.move).not.toHaveBeenCalled();83 expect(events.cancel).not.toHaveBeenCalled();84 expect(events.end).not.toHaveBeenCalled();85 browserTrigger(element, startEvent,{86 keys: [],87 x: 100,88 y: 2089 });90 expect(events.start).toHaveBeenCalled();91 expect(events.move).not.toHaveBeenCalled();92 expect(events.cancel).not.toHaveBeenCalled();93 expect(events.end).not.toHaveBeenCalled();94 browserTrigger(element, moveEvent,{95 keys: [],96 x: 140,97 y: 2098 });99 expect(events.start).toHaveBeenCalled();100 expect(events.move).toHaveBeenCalled();101 expect(events.cancel).not.toHaveBeenCalled();102 expect(events.end).not.toHaveBeenCalled();103 }));104 it('should not trigger a "move" without a "start"', inject(function($swipe) {105 $swipe.bind(element, events);106 expect(events.start).not.toHaveBeenCalled();107 expect(events.move).not.toHaveBeenCalled();108 expect(events.cancel).not.toHaveBeenCalled();109 expect(events.end).not.toHaveBeenCalled();110 browserTrigger(element, moveEvent,{111 keys: [],112 x: 100,113 y: 40114 });115 expect(events.start).not.toHaveBeenCalled();116 expect(events.move).not.toHaveBeenCalled();117 expect(events.cancel).not.toHaveBeenCalled();118 expect(events.end).not.toHaveBeenCalled();119 }));120 it('should not trigger an "end" without a "start"', inject(function($swipe) {121 $swipe.bind(element, events);122 expect(events.start).not.toHaveBeenCalled();123 expect(events.move).not.toHaveBeenCalled();124 expect(events.cancel).not.toHaveBeenCalled();125 expect(events.end).not.toHaveBeenCalled();126 browserTrigger(element, endEvent,{127 keys: [],128 x: 100,129 y: 40130 });131 expect(events.start).not.toHaveBeenCalled();132 expect(events.move).not.toHaveBeenCalled();133 expect(events.cancel).not.toHaveBeenCalled();134 expect(events.end).not.toHaveBeenCalled();135 }));136 it('should trigger a "start", many "move"s and an "end"', inject(function($swipe) {137 $swipe.bind(element, events);138 expect(events.start).not.toHaveBeenCalled();139 expect(events.move).not.toHaveBeenCalled();140 expect(events.cancel).not.toHaveBeenCalled();141 expect(events.end).not.toHaveBeenCalled();142 browserTrigger(element, startEvent,{143 keys: [],144 x: 100,145 y: 40146 });147 expect(events.start).toHaveBeenCalled();148 expect(events.move).not.toHaveBeenCalled();149 expect(events.cancel).not.toHaveBeenCalled();150 expect(events.end).not.toHaveBeenCalled();151 browserTrigger(element, moveEvent,{152 keys: [],153 x: 120,154 y: 40155 });156 browserTrigger(element, moveEvent,{157 keys: [],158 x: 130,159 y: 40160 });161 browserTrigger(element, moveEvent,{162 keys: [],163 x: 140,164 y: 40165 });166 browserTrigger(element, moveEvent,{167 keys: [],168 x: 150,169 y: 40170 });171 browserTrigger(element, moveEvent,{172 keys: [],173 x: 160,174 y: 40175 });176 browserTrigger(element, moveEvent,{177 keys: [],178 x: 170,179 y: 40180 });181 browserTrigger(element, moveEvent,{182 keys: [],183 x: 180,184 y: 40185 });186 expect(events.start).toHaveBeenCalled();187 expect(events.move.calls.length).toBe(7);188 expect(events.cancel).not.toHaveBeenCalled();189 expect(events.end).not.toHaveBeenCalled();190 browserTrigger(element, endEvent,{191 keys: [],192 x: 200,193 y: 40194 });195 expect(events.start).toHaveBeenCalled();196 expect(events.move.calls.length).toBe(7);197 expect(events.end).toHaveBeenCalled();198 expect(events.cancel).not.toHaveBeenCalled();199 }));200 it('should not start sending "move"s until enough horizontal motion is accumulated', inject(function($swipe) {201 $swipe.bind(element, events);202 expect(events.start).not.toHaveBeenCalled();203 expect(events.move).not.toHaveBeenCalled();204 expect(events.cancel).not.toHaveBeenCalled();205 expect(events.end).not.toHaveBeenCalled();206 browserTrigger(element, startEvent,{207 keys: [],208 x: 100,209 y: 40210 });211 expect(events.start).toHaveBeenCalled();212 expect(events.move).not.toHaveBeenCalled();213 expect(events.cancel).not.toHaveBeenCalled();214 expect(events.end).not.toHaveBeenCalled();215 browserTrigger(element, moveEvent,{216 keys: [],217 x: 101,218 y: 40219 });220 browserTrigger(element, moveEvent,{221 keys: [],222 x: 105,223 y: 40224 });225 browserTrigger(element, moveEvent,{226 keys: [],227 x: 110,228 y: 40229 });230 browserTrigger(element, moveEvent,{231 keys: [],232 x: 115,233 y: 40234 });235 browserTrigger(element, moveEvent,{236 keys: [],237 x: 120,238 y: 40239 });240 expect(events.start).toHaveBeenCalled();241 expect(events.move.calls.length).toBe(3);242 expect(events.cancel).not.toHaveBeenCalled();243 expect(events.end).not.toHaveBeenCalled();244 browserTrigger(element, endEvent,{245 keys: [],246 x: 200,247 y: 40248 });249 expect(events.start).toHaveBeenCalled();250 expect(events.move.calls.length).toBe(3);251 expect(events.end).toHaveBeenCalled();252 expect(events.cancel).not.toHaveBeenCalled();253 }));254 it('should stop sending anything after vertical motion dominates', inject(function($swipe) {255 $swipe.bind(element, events);256 expect(events.start).not.toHaveBeenCalled();257 expect(events.move).not.toHaveBeenCalled();258 expect(events.cancel).not.toHaveBeenCalled();259 expect(events.end).not.toHaveBeenCalled();260 browserTrigger(element, startEvent,{261 keys: [],262 x: 100,263 y: 40264 });265 expect(events.start).toHaveBeenCalled();266 expect(events.move).not.toHaveBeenCalled();267 expect(events.cancel).not.toHaveBeenCalled();268 expect(events.end).not.toHaveBeenCalled();269 browserTrigger(element, moveEvent,{270 keys: [],271 x: 101,272 y: 41273 });274 browserTrigger(element, moveEvent,{275 keys: [],276 x: 105,277 y: 55278 });279 browserTrigger(element, moveEvent,{280 keys: [],281 x: 110,282 y: 60283 });284 browserTrigger(element, moveEvent,{285 keys: [],286 x: 115,287 y: 70288 });289 browserTrigger(element, moveEvent,{290 keys: [],291 x: 120,292 y: 80293 });294 expect(events.start).toHaveBeenCalled();295 expect(events.cancel).toHaveBeenCalled();296 expect(events.move).not.toHaveBeenCalled();297 expect(events.end).not.toHaveBeenCalled();298 browserTrigger(element, endEvent,{299 keys: [],300 x: 200,301 y: 40302 });303 expect(events.start).toHaveBeenCalled();304 expect(events.cancel).toHaveBeenCalled();305 expect(events.move).not.toHaveBeenCalled();306 expect(events.end).not.toHaveBeenCalled();307 }));308 });309 }...
imehandler.js
Source:imehandler.js
1// Copyright 2010 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview Input Method Editors (IMEs) are OS-level widgets that make16 * it easier to type non-ascii characters on ascii keyboards (in particular,17 * characters that require more than one keystroke).18 *19 * When the user wants to type such a character, a modal menu pops up and20 * suggests possible "next" characters in the IME character sequence. After21 * typing N characters, the user hits "enter" to commit the IME to the field.22 * N differs from language to language.23 *24 * This class offers high-level events for how the user is interacting with the25 * IME in editable regions.26 *27 * Known Issues:28 *29 * Firefox always fires an extra pair of compositionstart/compositionend events.30 * We do not normalize for this.31 *32 * Opera does not fire any IME events.33 *34 * Spurious UPDATE events are common on all browsers.35 *36 * We currently do a bad job detecting when the IME closes on IE, and37 * make a "best effort" guess on when we know it's closed.38 *39 */40goog.provide('goog.events.ImeHandler');41goog.provide('goog.events.ImeHandler.Event');42goog.provide('goog.events.ImeHandler.EventType');43goog.require('goog.events.Event');44goog.require('goog.events.EventHandler');45goog.require('goog.events.EventTarget');46goog.require('goog.events.EventType');47goog.require('goog.events.KeyCodes');48goog.require('goog.userAgent');49goog.require('goog.userAgent.product');50/**51 * Dispatches high-level events for IMEs.52 * @param {Element} el The element to listen on.53 * @extends {goog.events.EventTarget}54 * @constructor55 */56goog.events.ImeHandler = function(el) {57 goog.base(this);58 /**59 * The element to listen on.60 * @type {Element}61 * @private62 */63 this.el_ = el;64 /**65 * Tracks the keyup event only, because it has a different life-cycle from66 * other events.67 * @type {goog.events.EventHandler}68 * @private69 */70 this.keyUpHandler_ = new goog.events.EventHandler(this);71 /**72 * Tracks all the browser events.73 * @type {goog.events.EventHandler}74 * @private75 */76 this.handler_ = new goog.events.EventHandler(this);77 if (goog.events.ImeHandler.USES_COMPOSITION_EVENTS) {78 this.handler_.79 listen(el, 'compositionstart', this.handleCompositionStart_).80 listen(el, 'compositionend', this.handleCompositionEnd_).81 listen(el, 'compositionupdate', this.handleTextModifyingInput_);82 }83 this.handler_.84 listen(el, 'textInput', this.handleTextInput_).85 listen(el, 'text', this.handleTextModifyingInput_).86 listen(el, goog.events.EventType.KEYDOWN, this.handleKeyDown_);87};88goog.inherits(goog.events.ImeHandler, goog.events.EventTarget);89/**90 * Event types fired by ImeHandler. These events do not make any guarantees91 * about whether they were fired before or after the event in question.92 * @enum {string}93 */94goog.events.ImeHandler.EventType = {95 // After the IME opens.96 START: 'startIme',97 // An update to the state of the IME. An 'update' does not necessarily mean98 // that the text contents of the field were modified in any way.99 UPDATE: 'updateIme',100 // After the IME closes.101 END: 'endIme'102};103/**104 * An event fired by ImeHandler.105 * @param {goog.events.ImeHandler.EventType} type The type.106 * @param {goog.events.BrowserEvent} reason The trigger for this event.107 * @constructor108 * @extends {goog.events.Event}109 */110goog.events.ImeHandler.Event = function(type, reason) {111 goog.base(this, type);112 /**113 * The event that triggered this.114 * @type {goog.events.BrowserEvent}115 */116 this.reason = reason;117};118goog.inherits(goog.events.ImeHandler.Event, goog.events.Event);119/**120 * Whether to use the composition events.121 * @type {boolean}122 */123goog.events.ImeHandler.USES_COMPOSITION_EVENTS =124 goog.userAgent.GECKO ||125 (goog.userAgent.WEBKIT && goog.userAgent.isVersion(532));126/**127 * Stores whether IME mode is active.128 * @type {boolean}129 * @private130 */131goog.events.ImeHandler.prototype.imeMode_ = false;132/**133 * The keyCode value of the last keyDown event. This value is used for134 * identiying whether or not a textInput event is sent by an IME.135 * @type {number}136 * @private137 */138goog.events.ImeHandler.prototype.lastKeyCode_ = 0;139/**140 * @return {boolean} Whether an IME is active.141 */142goog.events.ImeHandler.prototype.isImeMode = function() {143 return this.imeMode_;144};145/**146 * Handles the compositionstart event.147 * @param {goog.events.BrowserEvent} e The event.148 * @private149 */150goog.events.ImeHandler.prototype.handleCompositionStart_ =151 function(e) {152 this.handleImeActivate_(e);153};154/**155 * Handles the compositionend event.156 * @param {goog.events.BrowserEvent} e The event.157 * @private158 */159goog.events.ImeHandler.prototype.handleCompositionEnd_ = function(e) {160 this.handleImeDeactivate_(e);161};162/**163 * Handles the compositionupdate and text events.164 * @param {goog.events.BrowserEvent} e The event.165 * @private166 */167goog.events.ImeHandler.prototype.handleTextModifyingInput_ =168 function(e) {169 if (this.isImeMode()) {170 this.processImeComposition_(e);171 }172};173/**174 * Handles IME activation.175 * @param {goog.events.BrowserEvent} e The event.176 * @private177 */178goog.events.ImeHandler.prototype.handleImeActivate_ = function(e) {179 if (this.imeMode_) {180 return;181 }182 // Listens for keyup events to handle unexpected IME keydown events on older183 // versions of webkit.184 //185 // In those versions, we currently use textInput events deactivate IME186 // (see handleTextInput_() for the reason). However,187 // Safari fires a keydown event (as a result of pressing keys to commit IME188 // text) with keyCode == WIN_IME after textInput event. This activates IME189 // mode again unnecessarily. To prevent this problem, listens keyup events190 // which can use to determine whether IME text has been committed.191 if (goog.userAgent.WEBKIT &&192 !goog.events.ImeHandler.USES_COMPOSITION_EVENTS) {193 this.keyUpHandler_.listen(this.el_,194 goog.events.EventType.KEYUP, this.handleKeyUpSafari4_);195 }196 this.imeMode_ = true;197 this.dispatchEvent(198 new goog.events.ImeHandler.Event(199 goog.events.ImeHandler.EventType.START, e));200};201/**202 * Handles the IME compose changes.203 * @param {goog.events.BrowserEvent} e The event.204 * @private205 */206goog.events.ImeHandler.prototype.processImeComposition_ = function(e) {207 this.dispatchEvent(208 new goog.events.ImeHandler.Event(209 goog.events.ImeHandler.EventType.UPDATE, e));210};211/**212 * Handles IME deactivation.213 * @param {goog.events.BrowserEvent} e The event.214 * @private215 */216goog.events.ImeHandler.prototype.handleImeDeactivate_ = function(e) {217 this.imeMode_ = false;218 this.keyUpHandler_.removeAll();219 this.dispatchEvent(220 new goog.events.ImeHandler.Event(221 goog.events.ImeHandler.EventType.END, e));222};223/**224 * Handles a key down event.225 * @param {!goog.events.BrowserEvent} e The event.226 * @private227 */228goog.events.ImeHandler.prototype.handleKeyDown_ = function(e) {229 // Firefox and Chrome have a separate event for IME composition ('text'230 // and 'compositionupdate', respectively), other browsers do not.231 if (!goog.events.ImeHandler.USES_COMPOSITION_EVENTS) {232 var imeMode = this.isImeMode();233 // If we're in IE and we detect an IME input on keyDown then activate234 // the IME, otherwise if the imeMode was previously active, deactivate.235 if (!imeMode && e.keyCode == goog.events.KeyCodes.WIN_IME) {236 this.handleImeActivate_(e);237 } else if (imeMode && e.keyCode != goog.events.KeyCodes.WIN_IME) {238 if (goog.events.ImeHandler.isImeDeactivateKeyEvent_(e)) {239 this.handleImeDeactivate_(e);240 }241 } else if (imeMode) {242 this.processImeComposition_(e);243 }244 }245 // Safari on Mac doesn't send IME events in the right order so that we must246 // ignore some modifier key events to insert IME text correctly.247 if (goog.events.ImeHandler.isImeDeactivateKeyEvent_(e)) {248 this.lastKeyCode_ = e.keyCode;249 }250};251/**252 * Handles a textInput event.253 * @param {!goog.events.BrowserEvent} e The event.254 * @private255 */256goog.events.ImeHandler.prototype.handleTextInput_ = function(e) {257 // Some WebKit-based browsers including Safari 4 don't send composition258 // events. So, we turn down IME mode when it's still there.259 if (!goog.events.ImeHandler.USES_COMPOSITION_EVENTS &&260 goog.userAgent.WEBKIT &&261 this.lastKeyCode_ == goog.events.KeyCodes.WIN_IME &&262 this.isImeMode()) {263 this.handleImeDeactivate_(e);264 }265};266/**267 * Handles the key up event for any IME activity. This handler is just used to268 * prevent activating IME unnecessary in Safari at this time.269 * @param {!goog.events.BrowserEvent} e The event.270 * @private271 */272goog.events.ImeHandler.prototype.handleKeyUpSafari4_ = function(e) {273 if (this.isImeMode()) {274 switch (e.keyCode) {275 // These keyup events indicates that IME text has been committed or276 // cancelled. We should turn off IME mode when these keyup events277 // received.278 case goog.events.KeyCodes.ENTER:279 case goog.events.KeyCodes.TAB:280 case goog.events.KeyCodes.ESC:281 this.handleImeDeactivate_(e);282 break;283 }284 }285};286/**287 * Returns whether the given event should be treated as an IME288 * deactivation trigger.289 * @param {!goog.events.Event} e The event.290 * @return {boolean} Whether the given event is an IME deactivate trigger.291 * @private292 */293goog.events.ImeHandler.isImeDeactivateKeyEvent_ = function(e) {294 // Which key events involve IME deactivation depends on the user's295 // environment (i.e. browsers, platforms, and IMEs). Usually Shift key296 // and Ctrl key does not involve IME deactivation, so we currently assume297 // that these keys are not IME deactivation trigger.298 switch (e.keyCode) {299 case goog.events.KeyCodes.SHIFT:300 case goog.events.KeyCodes.CTRL:301 return false;302 default:303 return true;304 }305};306/** @override */307goog.events.ImeHandler.prototype.disposeInternal = function() {308 this.handler_.dispose();309 this.keyUpHandler_.dispose();310 this.el_ = null;311 goog.base(this, 'disposeInternal');...
actioneventwrapper_test.js
Source:actioneventwrapper_test.js
1// Copyright 2009 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.events.actionEventWrapperTest');15goog.setTestOnly('goog.events.actionEventWrapperTest');16goog.require('goog.a11y.aria');17goog.require('goog.a11y.aria.Role');18goog.require('goog.events');19goog.require('goog.events.EventHandler');20goog.require('goog.events.KeyCodes');21goog.require('goog.events.actionEventWrapper');22goog.require('goog.testing.events');23goog.require('goog.testing.jsunit');24var a, eh, events;25function setUpPage() {26 a = document.getElementById('a');27}28function setUp() {29 events = [];30 eh = new goog.events.EventHandler();31 assertEquals(32 'No listeners registered yet', 0, goog.events.getListeners(a).length);33}34function tearDown() {35 eh.dispose();36}37var Foo = function() {};38Foo.prototype.test = function(e) {39 events.push(e);40};41function assertListenersExist(el, listenerCount, capt) {42 var EVENT_TYPES = goog.events.ActionEventWrapper_.EVENT_TYPES_;43 for (var i = 0; i < EVENT_TYPES.length; ++i) {44 assertEquals(45 listenerCount,46 goog.events.getListeners(el, EVENT_TYPES[i], capt).length);47 }48}49function testAddActionListener() {50 var listener = function(e) { events.push(e); };51 goog.events.listenWithWrapper(a, goog.events.actionEventWrapper, listener);52 assertListenersExist(a, 1, false);53 goog.testing.events.fireClickSequence(a);54 assertEquals('1 event should have been dispatched', 1, events.length);55 assertEquals('Should be an click event', 'click', events[0].type);56 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);57 assertEquals('2 events should have been dispatched', 2, events.length);58 assertEquals('Should be a keypress event', 'keypress', events[1].type);59 goog.a11y.aria.setRole(60 /** @type {!Element} */ (a), goog.a11y.aria.Role.BUTTON);61 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);62 assertEquals('3 events should have been dispatched', 3, events.length);63 assertEquals('Should be a keyup event', 'keyup', events[2].type);64 assertTrue('Should be default prevented.', events[2].defaultPrevented);65 goog.a11y.aria.removeRole(/** @type {!Element} */ (a));66 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);67 assertEquals('3 events should have been dispatched', 3, events.length);68 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ESC);69 assertEquals('3 events should have been dispatched', 3, events.length);70 goog.a11y.aria.setRole(71 /** @type {!Element} */ (a), goog.a11y.aria.Role.TAB);72 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);73 assertEquals('4 events should have been dispatched', 4, events.length);74 assertEquals('Should be a keyup event', 'keyup', events[2].type);75 assertTrue('Should be default prevented.', events[2].defaultPrevented);76 goog.a11y.aria.removeRole(/** @type {!Element} */ (a));77 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);78 assertEquals('4 events should have been dispatched', 4, events.length);79 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ESC);80 assertEquals('4 events should have been dispatched', 4, events.length);81 goog.events.unlistenWithWrapper(a, goog.events.actionEventWrapper, listener);82 assertListenersExist(a, 0, false);83}84function testAddActionListenerForHandleEvent() {85 var listener = {handleEvent: function(e) { events.push(e); }};86 goog.events.listenWithWrapper(a, goog.events.actionEventWrapper, listener);87 assertListenersExist(a, 1, false);88 goog.testing.events.fireClickSequence(a);89 assertEquals('1 event should have been dispatched', 1, events.length);90 assertEquals('Should be an click event', 'click', events[0].type);91 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);92 assertEquals('2 events should have been dispatched', 2, events.length);93 assertEquals('Should be a keypress event', 'keypress', events[1].type);94 goog.a11y.aria.setRole(95 /** @type {!Element} */ (a), goog.a11y.aria.Role.BUTTON);96 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);97 assertEquals('3 events should have been dispatched', 3, events.length);98 assertEquals('Should be a keyup event', 'keyup', events[2].type);99 assertTrue('Should be default prevented.', events[2].defaultPrevented);100 goog.a11y.aria.removeRole(/** @type {!Element} */ (a));101 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);102 assertEquals('3 events should have been dispatched', 3, events.length);103 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ESC);104 assertEquals('3 events should have been dispatched', 3, events.length);105 goog.events.unlistenWithWrapper(a, goog.events.actionEventWrapper, listener);106 assertListenersExist(a, 0, false);107}108function testAddActionListenerInCaptPhase() {109 var count = 0;110 var captListener = function(e) {111 events.push(e);112 assertEquals(0, count);113 count++;114 };115 var bubbleListener = function(e) {116 events.push(e);117 assertEquals(1, count);118 count = 0;119 };120 goog.events.listenWithWrapper(121 a, goog.events.actionEventWrapper, captListener, true);122 goog.events.listenWithWrapper(123 a, goog.events.actionEventWrapper, bubbleListener);124 assertListenersExist(a, 1, false);125 assertListenersExist(a, 1, true);126 goog.testing.events.fireClickSequence(a);127 assertEquals('2 event should have been dispatched', 2, events.length);128 assertEquals('Should be an click event', 'click', events[0].type);129 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);130 assertEquals('4 events should have been dispatched', 4, events.length);131 assertEquals('Should be a keypress event', 'keypress', events[2].type);132 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);133 assertEquals('4 events should have been dispatched', 4, events.length);134 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ESC);135 assertEquals('4 events should have been dispatched', 4, events.length);136 goog.events.unlistenWithWrapper(137 a, goog.events.actionEventWrapper, captListener, true);138 goog.events.unlistenWithWrapper(139 a, goog.events.actionEventWrapper, bubbleListener);140 assertListenersExist(a, 0, false);141 assertListenersExist(a, 0, true);142}143function testRemoveActionListener() {144 var listener1 = function(e) { events.push(e); };145 var listener2 = function(e) { events.push({type: 'err'}); };146 goog.events.listenWithWrapper(a, goog.events.actionEventWrapper, listener1);147 assertListenersExist(a, 1, false);148 goog.events.listenWithWrapper(a, goog.events.actionEventWrapper, listener2);149 assertListenersExist(a, 2, false);150 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);151 assertEquals('2 events should have been dispatched', 2, events.length);152 assertEquals('Should be a keypress event', 'keypress', events[0].type);153 assertEquals('Should be an err event', 'err', events[1].type);154 goog.events.unlistenWithWrapper(a, goog.events.actionEventWrapper, listener2);155 assertListenersExist(a, 1, false);156 events = [];157 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);158 assertEquals('1 event should have been dispatched', 1, events.length);159 assertEquals('Should be a keypress event', 'keypress', events[0].type);160 goog.events.unlistenWithWrapper(a, goog.events.actionEventWrapper, listener1);161 assertListenersExist(a, 0, false);162}163function testEventHandlerActionListener() {164 var listener = function(e) { events.push(e); };165 eh.listenWithWrapper(a, goog.events.actionEventWrapper, listener);166 assertListenersExist(a, 1, false);167 goog.testing.events.fireClickSequence(a);168 assertEquals('1 event should have been dispatched', 1, events.length);169 assertEquals('Should be an click event', 'click', events[0].type);170 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);171 assertEquals('2 events should have been dispatched', 2, events.length);172 assertEquals('Should be a keypress event', 'keypress', events[1].type);173 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);174 assertEquals('2 events should have been dispatched', 2, events.length);175 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ESC);176 assertEquals('2 events should have been dispatched', 2, events.length);177 eh.unlistenWithWrapper(a, goog.events.actionEventWrapper, listener);178 assertListenersExist(a, 0, false);179}180function testEventHandlerActionListenerWithScope() {181 var foo = new Foo();182 var eh2 = new goog.events.EventHandler(foo);183 eh2.listenWithWrapper(a, goog.events.actionEventWrapper, foo.test);184 assertListenersExist(a, 1, false);185 goog.testing.events.fireClickSequence(a);186 assertEquals('1 event should have been dispatched', 1, events.length);187 assertEquals('Should be an click event', 'click', events[0].type);188 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ENTER);189 assertEquals('2 events should have been dispatched', 2, events.length);190 assertEquals('Should be a keypress event', 'keypress', events[1].type);191 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.SPACE);192 assertEquals('2 events should have been dispatched', 2, events.length);193 goog.testing.events.fireKeySequence(a, goog.events.KeyCodes.ESC);194 assertEquals('2 events should have been dispatched', 2, events.length);195 eh2.dispose();196 assertListenersExist(a, 0, false);197 delete foo;...
tests.py
Source:tests.py
...14 """15 fixtures = ['test_data.json']16 def setUp(self):17 logger.debug('Running CollisionTestCase')18 def create_events(self, prefix, periodical=False, days=None, weeks=None, **kwargs):19 # creates events distributed in time like this:20 # 07 08 09 10 11 12 13 14 15 16 17 18 1921 # |A---------------------------|22 # |B---| |C---------||D---||E---------| |F---||G---| |H---|23 # |X---------| |Y----|24 if days or weeks:25 periodical = True26 if periodical:27 dt = lambda h, m=0: datetime.time(h, m)28 model = models.SemesterEvent29 else:30 date = options.SEMESTER_START_DATE31 self.assertEqual(date.weekday(), 0, 'Semester start day is not Monday.')32 dt = lambda h, m=0: datetime.datetime.combine(date, datetime.time(h, m))33 model = models.OneTimeEvent34 events = {35 'a': model(start=dt(11), end=dt(16)),36 'b': model(start=dt(7), end=dt(8)),37 'c': model(start=dt(9), end=dt(11)),38 'd': model(start=dt(11), end=dt(12)),39 'e': model(start=dt(12), end=dt(14)),40 'f': model(start=dt(15), end=dt(16)),41 'g': model(start=dt(16), end=dt(17)),42 'h': model(start=dt(18), end=dt(19)),43 'x': model(start=dt(10), end=dt(12)),44 'y': model(start=dt(15, 30), end=dt(16, 30)),45 }46 for key, event in events.items():47 event.name = '%s %s %s' % ('semesterevent' if periodical else 'onetimeevent', prefix, key)48 if periodical:49 event.days = model.days.day_050 if days:51 event.days = 052 keys = model.days.keys()53 for i_day in days:54 self.assertGreater(len(keys), i_day, 'Mistake in test input parameters.')55 event.days |= getattr(model.days, keys[i_day])56 if weeks:57 event.weeks = 058 keys = model.weeks.keys()59 for i_week in weeks:60 self.assertGreater(len(keys), i_week, 'Mistake in test input parameters.')61 event.weeks |= getattr(model.weeks, keys[i_week])62 event.full_clean()63 event.save()64 for key, value in kwargs.items():65 if hasattr(event, key):66 setattr(event, key, value)67 return events68 def assert_events(self, events):69 if type(events) is dict:70 events = (events,)71 for i_events_dict in events:72 result_a = set()73 result_b = set()74 result_c = set()75 result_d = set()76 result_e = set()77 result_f = set()78 result_g = set()79 result_h = set()80 result_x = set()81 result_y = set()82 for j_events_dict in events:83 result_a.update([j_events_dict['d'], j_events_dict['e'], j_events_dict['f'], j_events_dict['x'], j_events_dict['y']])84 result_c.update([j_events_dict['x']])85 result_d.update([j_events_dict['a'], j_events_dict['x']])86 result_e.update([j_events_dict['a']])87 result_f.update([j_events_dict['a'], j_events_dict['y']])88 result_g.update([j_events_dict['y']])89 result_x.update([j_events_dict['a'], j_events_dict['c'], j_events_dict['d']])90 result_y.update([j_events_dict['a'], j_events_dict['f'], j_events_dict['g']])91 if j_events_dict != i_events_dict:92 result_a.update([j_events_dict['a']])93 result_b.update([j_events_dict['b']])94 result_c.update([j_events_dict['c']])95 result_d.update([j_events_dict['d']])96 result_e.update([j_events_dict['e']])97 result_f.update([j_events_dict['f']])98 result_g.update([j_events_dict['g']])99 result_h.update([j_events_dict['h']])100 result_x.update([j_events_dict['x']])101 result_y.update([j_events_dict['y']])102 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['a'])), result_a)103 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['b'])), result_b)104 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['c'])), result_c)105 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['d'])), result_d)106 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['e'])), result_e)107 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['f'])), result_f)108 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['g'])), result_g)109 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['h'])), result_h)110 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['x'])), result_x)111 self.assertSetEqual(set(functions.get_event_collisions(i_events_dict['y'])), result_y)112 def test_onetimeevents_room(self):113 room = data_models.Room.objects.first()114 events = self.create_events('room', rooms=[room])115 self.assert_events(events)116 def test_onetimeevents_user(self):117 user = data_models.User.objects.first()118 events = self.create_events('user')119 for key, event in events.items():120 data_models.UserEventConnection.objects.create(user=user, event=event, relation_type=options.USER_EVENT_RELATION_TYPES[0][0])121 self.assert_events(events)122 def test_onetimeevents_group(self):123 group = data_models.Group.objects.get(abbreviation='B-API-BIS')124 events = self.create_events('group', groups=[group])125 self.assert_events(events)126 def test_onetimeevents_activity(self):127 activity = data_models.ActivityDefinition.objects.first()128 events = self.create_events('activity', activities=[activity])129 self.assert_events(events)130 def test_semesterevents_room(self):131 room = data_models.Room.objects.first()132 events = self.create_events('room', periodical=True, rooms=[room])133 self.assert_events(events)134 def test_semesterevents_user(self):135 user = data_models.User.objects.first()136 events = self.create_events('user', periodical=True)137 for key, event in events.items():138 data_models.UserEventConnection.objects.create(user=user, event=event, relation_type=options.USER_EVENT_RELATION_TYPES[0][0])139 self.assert_events(events)140 def test_semesterevents_group(self):141 group = data_models.Group.objects.get(abbreviation='B-API-BIS')142 events = self.create_events('group', periodical=True, groups=[group])143 self.assert_events(events)144 def test_semesterevents_activity(self):145 activity = data_models.ActivityDefinition.objects.first()146 events = self.create_events('activity', periodical=True, activities=[activity])147 self.assert_events(events)148 def test_bothevents_room(self):149 room = data_models.Room.objects.first()150 events0 = self.create_events('room', rooms=[room])151 events1 = self.create_events('room periodical day_0', periodical=True, rooms=[room])152 events2 = self.create_events('room periodical day_1', days=[1,], rooms=[room])153 self.assert_events((events0, events1))154 self.assert_events(events2)155 def test_bothevents_user(self):156 user = data_models.User.objects.first()157 events0 = self.create_events('user')158 events1 = self.create_events('user periodical day_0', periodical=True)159 events2 = self.create_events('user periodical day_1', days=[1,])160 for key, event in events0.items():161 data_models.UserEventConnection.objects.create(user=user, event=event, relation_type=options.USER_EVENT_RELATION_TYPES[0][0])162 for key, event in events1.items():163 data_models.UserEventConnection.objects.create(user=user, event=event, relation_type=options.USER_EVENT_RELATION_TYPES[0][0])164 for key, event in events2.items():165 data_models.UserEventConnection.objects.create(user=user, event=event, relation_type=options.USER_EVENT_RELATION_TYPES[0][0])166 self.assert_events((events0, events1))167 self.assert_events(events2)168 def test_bothevents_group(self):169 group = data_models.Group.objects.get(abbreviation='B-API-BIS')170 events0 = self.create_events('group', groups=[group])171 events1 = self.create_events('group periodical day_0', periodical=True, groups=[group])172 events2 = self.create_events('group periodical day_1', days=[1,], groups=[group])173 self.assert_events((events0, events1))174 self.assert_events(events2)175 def test_bothevents_activity(self):176 activity = data_models.ActivityDefinition.objects.first()177 events0 = self.create_events('activity', activities=[activity])178 events1 = self.create_events('activity periodical day_0', periodical=True, activities=[activity])179 events2 = self.create_events('activity periodical day_1', days=[1,], activities=[activity])180 self.assert_events((events0, events1))...
actionhandler.js
Source:actionhandler.js
1// Copyright 2007 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview This file contains a class to provide a unified mechanism for16 * CLICK and enter KEYDOWN events. This provides better accessibility by17 * providing the given functionality to a keyboard user which is otherwise18 * would be available only via a mouse click.19 *20 * If there is an existing CLICK listener or planning to be added as below -21 *22 * <code>this.eventHandler_.listen(el, CLICK, this.onClick_);<code>23 *24 * it can be replaced with an ACTION listener as follows:25 *26 * <code>this.eventHandler_.listen(27 * new goog.events.ActionHandler(el),28 * ACTION,29 * this.onAction_);<code>30 *31 */32goog.provide('goog.events.ActionEvent');33goog.provide('goog.events.ActionHandler');34goog.provide('goog.events.ActionHandler.EventType');35goog.provide('goog.events.BeforeActionEvent');36goog.require('goog.events');37goog.require('goog.events.BrowserEvent');38goog.require('goog.events.EventTarget');39goog.require('goog.events.EventType');40goog.require('goog.events.KeyCodes');41goog.require('goog.userAgent');42/**43 * A wrapper around an element that you want to listen to ACTION events on.44 * @param {Element|Document} element The element or document to listen on.45 * @constructor46 * @extends {goog.events.EventTarget}47 */48goog.events.ActionHandler = function(element) {49 goog.events.EventTarget.call(this);50 /**51 * This is the element that we will listen to events on.52 * @type {Element|Document}53 * @private54 */55 this.element_ = element;56 goog.events.listen(element, goog.events.ActionHandler.KEY_EVENT_TYPE_,57 this.handleKeyDown_, false, this);58 goog.events.listen(element, goog.events.EventType.CLICK,59 this.handleClick_, false, this);60};61goog.inherits(goog.events.ActionHandler, goog.events.EventTarget);62/**63 * Enum type for the events fired by the action handler64 * @enum {string}65 */66goog.events.ActionHandler.EventType = {67 ACTION: 'action',68 BEFOREACTION: 'beforeaction'69};70/**71 * Key event type to listen for.72 * @type {string}73 * @private74 */75goog.events.ActionHandler.KEY_EVENT_TYPE_ = goog.userAgent.GECKO ?76 goog.events.EventType.KEYPRESS :77 goog.events.EventType.KEYDOWN;78/**79 * Handles key press events.80 * @param {!goog.events.BrowserEvent} e The key press event.81 * @private82 */83goog.events.ActionHandler.prototype.handleKeyDown_ = function(e) {84 if (e.keyCode == goog.events.KeyCodes.ENTER ||85 goog.userAgent.WEBKIT && e.keyCode == goog.events.KeyCodes.MAC_ENTER) {86 this.dispatchEvents_(e);87 }88};89/**90 * Handles mouse events.91 * @param {!goog.events.BrowserEvent} e The click event.92 * @private93 */94goog.events.ActionHandler.prototype.handleClick_ = function(e) {95 this.dispatchEvents_(e);96};97/**98 * Dispatches BeforeAction and Action events to the element99 * @param {!goog.events.BrowserEvent} e The event causing dispatches.100 * @private101 */102goog.events.ActionHandler.prototype.dispatchEvents_ = function(e) {103 var beforeActionEvent = new goog.events.BeforeActionEvent(e);104 // Allow application specific logic here before the ACTION event.105 // For example, Gmail uses this event to restore keyboard focus106 if (!this.dispatchEvent(beforeActionEvent)) {107 // If the listener swallowed the BEFOREACTION event, don't dispatch the108 // ACTION event.109 return;110 }111 // Wrap up original event and send it off112 var actionEvent = new goog.events.ActionEvent(e);113 try {114 this.dispatchEvent(actionEvent);115 } finally {116 // Stop propagating the event117 e.stopPropagation();118 }119};120/** @override */121goog.events.ActionHandler.prototype.disposeInternal = function() {122 goog.events.ActionHandler.superClass_.disposeInternal.call(this);123 goog.events.unlisten(this.element_, goog.events.ActionHandler.KEY_EVENT_TYPE_,124 this.handleKeyDown_, false, this);125 goog.events.unlisten(this.element_, goog.events.EventType.CLICK,126 this.handleClick_, false, this);127 delete this.element_;128};129/**130 * This class is used for the goog.events.ActionHandler.EventType.ACTION event.131 * @param {!goog.events.BrowserEvent} browserEvent Browser event object.132 * @constructor133 * @extends {goog.events.BrowserEvent}134 */135goog.events.ActionEvent = function(browserEvent) {136 goog.events.BrowserEvent.call(this, browserEvent.getBrowserEvent());137 this.type = goog.events.ActionHandler.EventType.ACTION;138};139goog.inherits(goog.events.ActionEvent, goog.events.BrowserEvent);140/**141 * This class is used for the goog.events.ActionHandler.EventType.BEFOREACTION142 * event. BEFOREACTION gives a chance to the application so the keyboard focus143 * can be restored back, if required.144 * @param {!goog.events.BrowserEvent} browserEvent Browser event object.145 * @constructor146 * @extends {goog.events.BrowserEvent}147 */148goog.events.BeforeActionEvent = function(browserEvent) {149 goog.events.BrowserEvent.call(this, browserEvent.getBrowserEvent());150 this.type = goog.events.ActionHandler.EventType.BEFOREACTION;151};...
events.py
Source:events.py
...7 def __init__(self, filename):8 self.file_manager = FileManager(filename)9 self.events = []10 self.specific_events = []11 def get_events(self):12 if not file_exists(self.file_manager.filename):13 self.events = []14 self.__save_events()15 return16 self.events = self.__load_events()17 if len(self.events) > 0:18 self.events = sorted(19 self.events, key=lambda e: datetime.strptime(e['date'], '%d.%m'))20 cei = self.__get_closest_event_index(datetime.now())21 self.events = self.events[cei:] + self.events[0:cei]22 def get_specific_events(self, start=0, duration=14):23 if not len(self.events) > 0:24 self.specific_events = []25 return26 if not start <= duration:27 print("Error! Incorrect values of arguments!")28 self.specific_events = []29 return30 s_date = datetime.now() + timedelta(days=start)31 si = self.__get_closest_event_index(s_date)32 e_date = datetime.now() + timedelta(days=duration+1)33 ei = self.__get_closest_event_index(e_date)34 if si <= ei:35 self.specific_events = self.events[si:ei]36 else:37 self.specific_events = self.events[si:] + self.events[0:ei]38 def add_event(self, name, day, month, year):39 event_id = str(uuid.uuid4())[0:5]40 date_string = "%s.%s" % (day, month)41 event = {}42 event["id"], event["name"] = event_id, name43 event["date"], event["year"] = date_string, year44 self.events.append(event)45 data = {}46 data['events'] = self.events47 self.file_manager.save_to_json_file(data)48 def edit_event(self, event_id, selected_attribute, value):49 events_with_id = [e for e in self.events if e["id"] == event_id]50 if len(events_with_id) == 0:51 print("There is no event with that id!")52 elif len(events_with_id) == 1:53 i = self.events.index(events_with_id[0])54 self.events[i][selected_attribute] = value55 self.__save_events()56 print("Event was successfully changed!")57 else:58 print("There was an error during editing!")59 def delete_event(self, event_id):60 events_with_id = [e for e in self.events if e["id"] == event_id]61 if len(events_with_id) == 0:62 print("There is no event with that id!")63 elif len(events_with_id) == 1:64 self.events.remove(events_with_id[0])65 self.__save_events()66 print("Event was successfully deleted!")67 else:68 print("There was an error during event deletion!")69 @staticmethod70 def __count_dates_difference(date_string, date_string_1):71 date = datetime.strptime(date_string, '%d.%m')72 date_1 = datetime.strptime(date_string_1, '%d.%m')73 difference = (date_1 - date).days74 if not difference < 0:75 return difference76 else:77 return difference + 36578 def __get_closest_event_index(self, date):79 date_string = "%s.%s" % (date.day, date.month)80 closest_event = min(81 self.events, key=lambda e: self.__count_dates_difference(date_string, e['date']))82 return self.events.index(closest_event)83 def __save_events(self):84 data = {}85 data['events'] = self.events86 self.file_manager.save_to_json_file(data)87 def __load_events(self):88 events_attribute_name = 'events'89 return self.file_manager.load_from_json_file(events_attribute_name)90 def load_events_from_txt_file(self, filename):91 if not file_exists(filename):92 return []93 lines = self.file_manager.load_lines_from_txt_file(filename)94 names = lines[::3]95 dates = lines[1::3]96 if not len(names) == len(dates):97 return []98 for i in range(len(names)):99 name = names[i].rstrip("\n")100 sd = dates[i].rstrip("\n").split(".")101 day, month, year = sd[0], sd[1], sd[2]102 self.add_event(name, day, month, year)103 self.__save_events()...
event_controller.py
Source:event_controller.py
...5import repositories.member_repository as member_repository6events_blueprint = Blueprint("events", __name__)7# INDEX - View all Events (classes) along with event type8@events_blueprint.route("/events")9def events():10 events = event_repository.select_all() # NEW11 return render_template("events/index.html", events=events)12 13# GET new event14@events_blueprint.route("/events/new")15def new_event():16 members = member_repository.select_all()17 return render_template("events/new.html", members=members)18# CREATE new events - posts to server19@events_blueprint.route("/events", methods=['POST'])20def create_event():21 name = request.form['name']22 category = request.form['category']23 status = request.form['status']24 member_id = request.form['member_id']25 member = member_repository.select(member_id)26 event = Event(name, category, status, member)27 event_repository.save(event)28 return redirect('/events')29#Show/View30@events_blueprint.route("/events/<id>", methods=['GET'])31def show_event(id):32 event = event_repository.select(id)33 return render_template("events/show.html", event=event)34# EDIT35# GET '/events/<id>/edit'36@events_blueprint.route("/events/<id>/edit", methods=['GET'])37def edit_event(id):38 event = event_repository.select(id)39 members = member_repository.select_all()40 return render_template('events/edit.html', event=event, members=members)41# UPDATE42@events_blueprint.route("/events/<id>", methods=['POST'])43def update_event(id):44 name = request.form['name']45 category = request.form['category']46 status = request.form['status']47 member_id = request.form['member_id']48 # member = member_repository.select()49 50 member = member_repository.select(member_id)51 event = Event(name, category, status, member, id)52 event_repository.update(event)53 return redirect('/events')54# DELETE55@events_blueprint.route("/events/<id>/delete", methods=['POST'])56def delete_event(id):57 event_repository.delete(id)58 return redirect('/events')59# @events_blueprint.route("/events")60# def events():61# events = event_repository.select_all() # NEW62# return render_template("events/index.html", events = events)63# @events_blueprint.route("/events/<id>")64# def show(id):65# event = event_repository.select(id)66# users = event_repository.users(event)...
Using AI Code Generation
1var events = require('events');2var eventEmitter = new events.EventEmitter();3var myEventHandler = function(){4 console.log('I hear a scream!');5};6eventEmitter.on('scream', myEventHandler);7eventEmitter.emit('scream');8var fs = require('fs');9fs.appendFile('mynewfile2.txt', 'Hello content!', function(err){10 if(err) throw err;11 console.log('Saved!');12});13fs.appendFile('mynewfile2.txt', 'This is my text.', function(err){14 if(err) throw err;15 console.log('Saved!');16});17fs.writeFile('mynewfile3.txt', 'This is my text', function(err){18 if(err) throw err;19 console.log('Saved!');20});21fs.writeFile('mynewfile3.txt', 'This is my text', function(err){22 if(err) throw err;23 console.log('Saved!');24});25fs.writeFile('mynewfile3.txt', 'This is my text', function(err){26 if(err) throw err;27 console.log('Saved!');28});29fs.writeFile('mynewfile3.txt', 'This is my text', function(err){30 if(err) throw err;31 console.log('Saved!');32});33fs.writeFile('mynewfile3.txt', 'This is my text', function(err){34 if(err) throw err;35 console.log('Saved!');36});37fs.writeFile('mynewfile3.txt', 'This is my text', function(err){38 if(err) throw err;39 console.log('Saved!');40});41fs.writeFile('mynewfile3.txt
Using AI Code Generation
1var ghost = require('ghostjs'),2 assert = require('assert');3 .type('input[name="q"]', 'GhostJS')4 .click('input[name="btnG"]')5 .waitForUrl(/q=ghostjs/)6 .title(function(err, title) {7 assert.equal(title, 'GhostJS - Google Search');8 })9 .screenshot('test.png')10 .end();11### ghost.open(url, [callback])12### ghost.close([callback])13### ghost.end([callback])14### ghost.screenshot(filename, [callback])15### ghost.title(callback)16### ghost.url(callback)17### ghost.html(callback)18### ghost.exists(selector, callback)19### ghost.visible(selector, callback)20### ghost.click(selector, [callback])21### ghost.type(selector, text, [callback])22### ghost.clear(selector, [callback])23### ghost.value(selector, callback)24### ghost.select(selector, value, [callback])25### ghost.waitForUrl(url, [callback])26### ghost.waitForText(selector, text, [callback])27### ghost.waitForExists(selector, [callback])
Using AI Code Generation
1var ghost = require('ghostjs');2var events = require('events');3var eventEmitter = new events.EventEmitter();4var myEventHandler = function () {5 console.log('I hear a scream!');6}7eventEmitter.on('scream', myEventHandler);8eventEmitter.emit('scream');9 return ghost.fill('#lst-ib', 'Ghostjs');10}).then(function() {11 return ghost.click('#tsbb');12}).then(function() {13 return ghost.wait(1000);14}).then(function() {15 return ghost.screenshot('test.png');16}).then(function() {17 return ghost.close();18}).then(function() {19 console.log('Done');20}).catch(function(e) {21 console.log(e.stack);22});23var ghost = require('ghostjs');24var assert = require('assert');25var events = require('events');26var eventEmitter = new events.EventEmitter();27var myEventHandler = function () {28 console.log('I hear a scream!');29}30eventEmitter.on('scream', myEventHandler);31eventEmitter.emit('scream');32describe('Google', function() {33 it('should find Ghostjs', function() {34 return ghost.fill('#lst-ib', 'Ghostjs');35 }).then(function() {36 return ghost.click('#tsbb');37 }).then(function() {38 return ghost.wait(1000);39 }).then(function() {40 return ghost.screenshot('test.png');41 }).then(function() {42 return ghost.close();43 }).then(function() {44 console.log('Done');45 }).catch(function(e) {46 console.log(e.stack);47 });48 });49});50var ghost = require('ghostjs');51var assert = require('assert');52var events = require('events');53var eventEmitter = new events.EventEmitter();54var myEventHandler = function () {55 console.log('I hear a scream!');56}
Using AI Code Generation
1var ghost = require('ghostjs');2 ghost.type('input[name="q"]', 'Hello World', function() {3 ghost.press('enter', function() {4 ghost.wait(2000, function() {5 ghost.screenshot('google.png', function() {6 ghost.exit();7 });8 });9 });10 });11});12### ghost.open(url, callback)13### ghost.click(selector, callback)14### ghost.type(selector, text, callback)15### ghost.press(key, callback)16### ghost.wait(milliseconds, callback)17### ghost.screenshot(filename, callback)18### ghost.exit()19### ghost.on(event, callback)20### ghost.set(key, value, callback)21### ghost.get(key, callback)22### ghost.evaluate(callback)23### ghost.injectJs(filename, callback)
Using AI Code Generation
1const ghostjs = require('ghostjs');2 .type('input[name="q"]', 'Hello World')3 .click('input[name="btnK"]')4 .wait('#resultStats')5 .screenshot('hello_world.png')6 .then(() => {7 console.log('done');8 })9 .catch((err) => {10 console.log(err);11 });12### open(url)13### type(selector, text)14### click(selector)15### submit(selector)16### wait(selector)17### screenshot(path)18### evaluate(fn, ...args)19### close()20### get(url)21### post(url, data)22### put(url, data)23### delete(url)24### on(eventName, handler)25### off(eventName, handler)
Using AI Code Generation
1var ghost = require('ghostjs');2 ghost.fill('#lst-ib', 'GhostJS', function() {3 ghost.press('enter', function() {4 ghost.wait(5000, function() {5 ghost.screenshot('google.png', function() {6 ghost.exit();7 });8 });9 });10 });11});
Using AI Code Generation
1var ghost = require('ghostjs');2var assert = require('assert');3 ghost.fill('#lst-ib', 'ghostjs', function() {4 ghost.press('ENTER', function() {5 ghost.wait(function() {6 return document.title.indexOf('ghostjs') !== -1;7 }, function() {8 ghost.screenshot('test.png', function() {9 ghost.exit();10 });11 });12 });13 });14});15#### `ghost.open(url, [callback])`16#### `ghost.wait(callback, [callback])`17#### `ghost.fill(selector, value, [callback])`18#### `ghost.click(selector, [callback])`19#### `ghost.press(key, [callback])`20#### `ghost.screenshot(filename, [callback])`21#### `ghost.exit([callback])`22#### `ghost.evaluate(callback, [callback])`23#### `ghost.injectJs(filename, [callback])`24#### `ghost.injectCss(filename, [callback])`25#### `ghost.setHeaders(headers, [callback])`26#### `ghost.setHeaders(headers, [callback])
Using AI Code Generation
1var ghost = require('ghostjs');2 ghost.sendKeys('input[name="q"]', 'GhostJS');3 ghost.click('input[name="btnG"]');4 ghost.wait(5000, function() {5 ghost.screenshot('google.png');6 ghost.exit();7 });8});9var ghost = require('ghostjs');10 .sendKeys('input[name="q"]', 'GhostJS')11 .click('input[name="btnG"]')12 .wait(5000)13 .screenshot('google.png')14 .exit();
Using AI Code Generation
1const ghost = require('ghostjs');2const events = require('events');3const eventEmitter = new events.EventEmitter();4eventEmitter.on('navigate', function (url) {5 ghost.open(url);6 ghost.waitPageLoad();7 ghost.wait(5000);8 ghost.capture('google.png');9 ghost.exit();10});11eventEmitter.emit('navigate', url);
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!!