How to use Handler method in argos

Best JavaScript code snippet using argos

main.js

Source:main.js Github

copy

Full Screen

...34 //this way we can do style.block and style.none to display and hide menus35 var menus = new Menus(document, auxMisc["menusArray"]);36 //used to change background colour37 var body = document.getElementsByTagName("body")[0];38 function initEndHandler(ev){39 window.removeEventListener("initEnd", initEndHandler);40 firstMenu(menus, auxMisc, musics, body);41 menuListeners(auxMisc, menus, buttons, imgs, sounds, musics, body, domSpaceships(menus), domAux, player);42 }43 function initSoundsEndHandler(ev){44 window.removeEventListener("initSoundsEnd", initSoundsEndHandler);45 window.addEventListener("initEnd", initEndHandler);46 calculateMonitorRefreshRate(auxMisc);47 }48 function initMusicsEndHandler(ev){49 window.removeEventListener("initMusicsEnd", initMusicsEndHandler);50 window.addEventListener("initSoundsEnd", initSoundsEndHandler);51 //load the sounds of the game52 nToLoad = {"rockets" : 1 , "buttons" : 2 ,"esc" : 2 };53 sounds = {"rockets" : [], "buttons" : [],"esc" : []};54 initSounds(nToLoad, sounds);55 }56 function initImagesEndHandler(ev){57 window.removeEventListener("initImagesEnd", initImagesEndHandler);58 window.addEventListener("initMusicsEnd", initMusicsEndHandler);59 //load the music of the game60 nToLoad = {"campain" : 3 ,"endless" : 1 , "boss" : 2 ,"music": 1 };61 musics = {"campain" : [],"endless" : [], "boss" : [],"music": []};62 initMusics(nToLoad, musics);63 }64 function initMenuEndHandler(ev){65 window.removeEventListener("initMenuEnd", initMenuEndHandler);66 window.addEventListener("initImagesEnd", initImagesEndHandler);67 //load the imagens of the game68 var nToLoad = { "spaceship" : 5 , "enemies" : 2 , "boss" : 2 , "asteroids" : 1 , "powerups" : 9 , "others" : 1, "rockets" : 1 , "enemyRockets" : 1 , "background" : 1 , "explosions" : 1 , "gameover" : 2 , "win" : 1 };69 var nLoaded = { "spaceship" : 0 , "enemies" : 0 , "boss" : 0 , "asteroids" : 0 , "powerups" : 0 , "others" : 0, "rockets" : 0 , "enemyRockets" : 0 , "background" : 0 , "explosions" : 0 , "gameover" : 0 , "win" : 0 };70 imgs = { "spaceship" : [], "enemies" : [], "boss" : [], "asteroids" : [], "powerups" : [], "others" : [],"rockets" : [], "enemyRockets" : [], "background" : [], "explosions" : [], "gameover" : [], "win" : []};71 72 initImages(nLoaded, nToLoad, imgs, imgsMenu);73 }74 window.addEventListener("initMenuEnd", initMenuEndHandler);75 76 initMenu(nLoaded, nToLoad, imgsMenu);77 //pause78 var muteM = document.getElementById("pauseMenu_0");79 buttons["pauseMenu"].push(muteM);80 var volumeLowM = document.getElementById("pauseMenu_1");81 buttons["pauseMenu"].push(volumeLowM);82 var volumeHighM = document.getElementById("pauseMenu_2");83 buttons["pauseMenu"].push(volumeHighM);84 85 var muteS = document.getElementById("pauseMenu_3");86 buttons["pauseMenu"].push(muteS);87 var volumeLowS = document.getElementById("pauseMenu_4");88 buttons["pauseMenu"].push(volumeLowS);89 var volumeHighS = document.getElementById("pauseMenu_5");90 buttons["pauseMenu"].push(volumeHighS);91 var back = document.getElementById("pauseMenu_6");92 buttons["pauseMenu"].push(back);93 //startMenu94 var startButon = document.getElementById("startMenu_0");95 buttons["startMenu"].push(startButon);96 //loginRegMenu97 var signUpButon = document.getElementById("loginRegMenu_0");98 buttons["loginRegMenu"].push(signUpButon);99 var loginButon = document.getElementById("loginRegMenu_1");100 buttons["loginRegMenu"].push(loginButon);101 //popUpMenu102 var yesButon = document.getElementById("popUpMenu_0");103 buttons["popUpMenu"].push(yesButon);104 var okButon = document.getElementById("popUpMenu_1");105 buttons["popUpMenu"].push(okButon);106 var noButon = document.getElementById("popUpMenu_2");107 buttons["popUpMenu"].push(noButon);108 //mainMenu109 var campain = document.getElementById("mainMenu_0");110 buttons["mainMenu"].push(campain);111 var endless = document.getElementById("mainMenu_1");112 buttons["mainMenu"].push(endless);113 var editor = document.getElementById("mainMenu_2");114 buttons["mainMenu"].push(editor);115 var leave = document.getElementById("mainMenu_3");116 buttons["mainMenu"].push(leave);117 var help = document.getElementById("mainMenu_4");118 buttons["mainMenu"].push(help);119 var credits = document.getElementById("mainMenu_5");120 buttons["mainMenu"].push(credits);121 var leaderBoard = document.getElementById("mainMenu_6");122 buttons["mainMenu"].push(leaderBoard);123 var controls = document.getElementById("mainMenu_7");124 buttons["mainMenu"].push(controls);125 //levelMenu126 var level1 = document.getElementById("levelMenu_0");127 buttons["levelMenu"].push(level1);128 var level2 = document.getElementById("levelMenu_1");129 buttons["levelMenu"].push(level2);130 var level3 = document.getElementById("levelMenu_2");131 buttons["levelMenu"].push(level3);132 var speedrun = document.getElementById("levelMenu_3");133 buttons["levelMenu"].push(speedrun);134 var back = document.getElementById("levelMenu_4");135 buttons["levelMenu"].push(back);136 //chooseSpaceshipMenu137 var left = document.getElementById("chooseSpaceshipMenu_0");138 buttons["chooseSpaceshipMenu"].push(left);139 var right = document.getElementById("chooseSpaceshipMenu_1");140 buttons["chooseSpaceshipMenu"].push(right);141 var go = document.getElementById("chooseSpaceshipMenu_2");142 buttons["chooseSpaceshipMenu"].push(go);143 var backChooseSpaceship = document.getElementById("chooseSpaceshipMenu_3");144 buttons["chooseSpaceshipMenu"].push(backChooseSpaceship);145 //creditsMenu146 var backCredits = document.getElementById("creditsMenu_0");147 buttons["creditsMenu"].push(backCredits);148 //helpMenu149 var backHelp = document.getElementById("helpMenu_0");150 buttons["helpMenu"].push(backHelp);151 var nextHelp = document.getElementById("helpMenu_1");152 buttons["helpMenu"].push(nextHelp);153 //controlsMenu154 var backControl = document.getElementById("controlsMenu_0");155 buttons["controlsMenu"].push(backControl);156 var nextControl = document.getElementById("controlsMenu_1");157 buttons["controlsMenu"].push(nextControl);158 var playControl = document.getElementById("controlsMenu_2");159 buttons["controlsMenu"].push(playControl);160 //leaderBoard161 var leaderBoardBack = document.getElementById("leaderBoard_0");162 buttons["leaderBoard"].push(leaderBoardBack);163}164function initMenu(nLoaded, nToLoad, imgsMenu){165 var numToLoad = 0;166 //Images load handler167 function imgMenuLoad(ev){168 var img = ev.target;169 let key = img.id.split("_")[0];170 nLoaded[key] += 1;171 if (allLoaded(nLoaded, numToLoad) == true){172 var evInitMenuEnd = new Event("initMenuEnd");173 window.dispatchEvent(evInitMenuEnd);174 }175 }176 for (let toLoad in nToLoad){177 numToLoad += nToLoad[toLoad];178 }179 for (let key in imgsMenu){180 for (var i = 0; i < nToLoad[key]; i++ ){181 imgsMenu[key][i] = new Image(); 182 imgsMenu[key][i].addEventListener("load", imgMenuLoad);183 imgsMenu[key][i].id = [key]+"_" + i;184 imgsMenu[key][i].src = "resources/menu/"+[key]+"_" + i + ".png"; //dá ordem de loadmento da imagem185 }186 }187}188function initImages(nLoaded, nToLoad, imgs, imgsMenu){189 var numToLoad = 0;190 //Images load handler191 function imgLoad(ev){192 var img = ev.target;193 let key = img.id.split("_")[0];194 nLoaded[key] += 1;195 if (allLoaded(nLoaded, numToLoad) == true){196 var evInitImagesEnd = new Event("initImagesEnd");197 imgs["imgsMenus"] = imgsMenu;198 window.dispatchEvent(evInitImagesEnd);199 }200 }201 for (let toLoad in nToLoad){202 numToLoad += nToLoad[toLoad];203 }204 for (let key in imgs){205 for (var i = 0; i < nToLoad[key]; i++ ){206 imgs[key][i] = new Image(); 207 imgs[key][i].addEventListener("load", imgLoad);208 imgs[key][i].id = [key]+"_" + i;209 imgs[key][i].src = "resources/game/"+[key]+"_" + i + ".png"; //dá ordem de loadmento da imagem210 }211 }212}213function initMusics(nToLoad, musics){214 for (let key in musics){215 for (var i = 0; i < nToLoad[key]; i++ ){216 musics[key][i] = new Audio();217 musics[key][i].id = [key]+"_" + i;218 musics[key][i].src = "resources/musics/"+[key]+"_" + i + ".mp3"; //dá ordem de loadmento da imagem219 }220 }221 var evInitEnd = new Event("initMusicsEnd");222 window.dispatchEvent(evInitEnd);223}224function initSounds(nToLoad, sounds){225 for (let key in sounds){226 for (var i = 0; i < nToLoad[key]; i++ ){227 sounds[key][i] = new Audio();228 sounds[key][i].id = [key]+"_" + i;229 sounds[key][i].src = "resources/sounds/"+[key]+"_" + i + ".mp3"; //dá ordem de loadmento da imagem230 }231 }232 var evInitEnd = new Event("initSoundsEnd");233 window.dispatchEvent(evInitEnd);234}235function calculateMonitorRefreshRate(auxMisc){236 var i = 0;237 var totalTime = 0;238 var oldtime = 0;239 var refreshRate;240 var oldRefreshRate = 0;241 var requestId;242 function aux(time){243 if(oldtime > 0){244 oldRefreshRate = refreshRate;245 refreshRate = Math.round(1000/(time - oldtime));246 if(refreshRate == oldRefreshRate){247 auxMisc["fps"] = refreshRate;248 window.cancelAnimationFrame(requestId);249 var evInitEnd = new Event("initEnd");250 window.dispatchEvent(evInitEnd);251 return;252 }253 }254 /*if(i > 0){255 totalTime += time - oldtime;256 257 if(i >= 5){258 auxMisc["fps"] = Math.round(1000/(totalTime/5));259 window.cancelAnimationFrame(requestId);260 var evInitEnd = new Event("initEnd");261 window.dispatchEvent(evInitEnd);262 return;263 }264 }265 i++;*/266 oldtime = time;267 requestId = window.requestAnimationFrame(aux);268 }269 requestId = window.requestAnimationFrame(aux);270}271function allLoaded(nLoaded,numToLoad){272 var sumLoaded = 0;273 for(let lo in nLoaded){274 sumLoaded += nLoaded[lo];275 }276 if(sumLoaded == numToLoad){277 return true;278 }else{279 return false;280 }281}282function menuListeners(auxMisc, menus, buttons, imgs, sounds, musics, body, spaceships, domAux, player){283 var auxKeyDownHandler = function(ev){284 KeyDownHandler(ev, buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);285 }286 var auxClickHandler = function(ev){287 sounds["buttons"][1].load();288 sounds["buttons"][1].play().catch(function(){});289 290 //which button?291 switch(ev.target.id){292 //PAUSA--------------293 //mute294 case("pauseMenu_0"): 295 muteClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);296 break;297 case("pauseMenu_1"): 298 somLowClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);299 break;300 case("pauseMenu_2"):301 somHighClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);302 break;303 case("pauseMenu_3"): 304 muteClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);305 break;306 case("pauseMenu_4"): 307 somLowClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);308 break;309 case("pauseMenu_5"):310 somHighClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);311 break;312 case("pauseMenu_6"):313 leaveDoGameClickHandler(auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux);314 break;315 //START------------316 case("startMenu_0"):317 startClickHandler(ev, menus, auxMisc);318 break;319 //LOGIN REG------------320 //signUp321 case("loginRegMenu_0"):322 signUpClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);323 break;324 //login325 case("loginRegMenu_1"):326 loginClickHandler(menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);327 break;328 //POP UP------------329 //yes330 case("popUpMenu_0"):331 yesClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);332 break;333 //ok334 case("popUpMenu_1"):335 okClickHandler(ev, menus, auxMisc, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);336 break;337 //no338 case("popUpMenu_2"):339 noClickHandler(ev, menus, auxMisc, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);340 break;341 //MAIN MENU------------342 //campain343 case("mainMenu_0"): 344 campainClickHandler(ev, auxMisc, menus, domAux);345 break;346 //endless347 case("mainMenu_1"):348 endlessClickHandler(ev, auxMisc, menus, buttons, body, spaceships,imgs);349 break;350 case("mainMenu_2"):351 console.log("editor");352 break;353 //closes game354 case("mainMenu_3"): 355 closesGameClickHandler(ev, auxMisc, sounds, musics, menus, body); 356 break;357 //help358 case("mainMenu_4"):359 helpClickHandler(ev, menus, auxMisc, body);360 break;361 //credits362 case("mainMenu_5"): 363 creditsClickHandler(ev, menus, auxMisc, domAux);364 break;365 366 //leaderBoard367 case("mainMenu_6"): 368 leaderBoardClickHandler(ev, menus, auxMisc, body, domAux);369 break; 370 371 //controls372 case("mainMenu_7"): 373 controlsClickHandler(ev, menus, auxMisc, body);374 break; 375 //LEVEL MENU------------376 //level 1377 case("levelMenu_0"): 378 levelClickHandler(ev, auxMisc, menus, buttons, body, 1, spaceships, imgs);379 break;380 case("levelMenu_1"): 381 levelClickHandler(ev, auxMisc, menus, buttons, body, 2, spaceships, imgs);382 break;383 case("levelMenu_2"):384 levelClickHandler(ev, auxMisc, menus, buttons, body, 3, spaceships, imgs);385 break;386 case("levelMenu_3"):387 speedrunClickHandler(ev, auxMisc, menus, buttons, body, spaceships, imgs);388 break;389 //back390 case("levelMenu_4"):391 levelMenuBack(ev, menus, auxMisc);392 break;393 //CHOOSE SPACESHIP MENU------------394 //left395 case("chooseSpaceshipMenu_1"): 396 leftClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs);397 break;398 //right399 case("chooseSpaceshipMenu_0"): 400 rightClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs);401 break;402 //play403 case("chooseSpaceshipMenu_2"):404 playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);405 break;406 //back407 case("chooseSpaceshipMenu_3"):408 chooseSpaceshipsMenuBack(ev, menus, auxMisc, body);409 break;410 //LEADERBOARD------------411 //back412 case("leaderBoard_0"):413 leaderBoardBackClickHandler(ev, menus, auxMisc, body);414 break;415 //CREDITS MENU------------416 //back417 case("creditsMenu_0"):418 creditsBackClickHandler(ev, menus, auxMisc);419 break;420 //CONTROLS MENU------------421 //back422 case("controlsMenu_0"):423 controlsBackClickHandler(ev, menus, auxMisc, body, buttons, player);424 break;425 case("controlsMenu_1"):426 controlsNextClickHandler(ev, menus, auxMisc, body, buttons, player);427 break; 428 case("controlsMenu_2"):429 controlsPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);430 break;431 //HELP MENU------------432 //back433 case("helpMenu_0"):434 helpBackClickHandler(ev, menus, auxMisc, body, player);435 break;436 //next437 case("helpMenu_1"):438 helpPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);439 break;440 }441 }442 var auxMouseInHandler = function(ev){443 let key = ev.target.id.split("_")[0];444 let index = ev.target.id.split("_")[1];445 buttons[key][index].style.opacity = 0.7;446 buttons[key][index].style.cursor = "pointer";447 sounds["buttons"][0].load();448 sounds["buttons"][0].play().catch(function(){});449 }450 var auxMouseOutHandler = function(ev){451 let key = ev.target.id.split("_")[0];452 let index = ev.target.id.split("_")[1];453 buttons[key][index].style.opacity = 1;454 buttons[key][index].style.cursor = "default";455 }456 //LISTENERS vvvvv457 window.addEventListener("keydown",auxKeyDownHandler); 458 //if he is coming from the game and he didnt unlock fillerText Henrique459 if (auxMisc["oldMenu"] == "chooseSpaceshipMenu" && menus["popUpMenu"].style.display == ""){460 for(let key in buttons){461 if(key != "pauseMenu"){462 for ( var i = 0; i < Object.keys(buttons[key]).length; i++){463 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);464 }465 }466 }467 //beggining468 }else if(auxMisc["oldMenu"] == "fillerText"){469 for(let key in buttons){470 for ( var i = 0; i < Object.keys(buttons[key]).length; i++){471 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);472 }473 }474 //if he is coming from a game and he unlocked a spaceship475 }else if(auxMisc["oldMenu"] == "chooseSpaceshipMenu" && menus["popUpMenu"].style.display == "block"){476 for(let key in buttons){477 if(key == "popUpMenu"){478 for ( var i = 0; i < Object.keys(buttons[key]).length; i++){479 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);480 }481 }482 }483 }484 //LISTENERS ^^^^^^485}486function EnterPress( menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux){487 if(auxMisc["currentMenu"] == "loginRegMenu"){488 loginClickHandler( menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux)489 }490}491//Handlers vvvvvv492function KeyDownHandler(ev, buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){493 switch(ev.code) {494 case "Escape": togglePauseMenu(buttons, menus, auxMisc, sounds, musics, auxClickHandler, auxMouseInHandler, auxMouseOutHandler); break;495 case "Enter": EnterPress(menus, auxMisc, musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux); break;496 case "KeyP":497 auxMisc["secretProgress"] += "P";498 if(auxMisc["secretPress"].indexOf(auxMisc["secretProgress"]) != 0){499 auxMisc["secretProgress"] = "P";500 }501 else if(auxMisc["secretPress"] == auxMisc["secretProgress"]){502 var unlockingSpaceship = 4;503 unlockSpaceship(unlockingSpaceship, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player);504 }505 break;506 default: secret(ev, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player);break;507 508 }509}510// PAUSE -------511function muteClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){512 for(let key in musics){513 for ( let i = 0; i < Object.keys(musics[key]).length; i++){514 musics[key][i].volume = 0;515 }516 }517 518 buttons["pauseMenu"][0].style.opacity = 0.3;519 buttons["pauseMenu"][0].style.cursor = "default";520 removeEVLButtons(buttons, "pauseMenu", 0, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);521 522 buttons["pauseMenu"][1].style.opacity = 0.3;523 buttons["pauseMenu"][1].style.cursor = "default";524 removeEVLButtons(buttons, "pauseMenu", 1, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);525 //sound goes from 1 to 0526 buttons["pauseMenu"][2].style.opacity = 1;527 addEVLButtons(buttons, "pauseMenu", 2, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);528}529function somLowClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){530 console.log("-M"); 531 532 //place volume up button again533 if (musics["music"][0].volume + 0.2 > 1){534 buttons["pauseMenu"][2].style.opacity = 1;535 addEVLButtons(buttons, "pauseMenu", 2, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);536 }537 for(let key in musics){538 for ( let i = 0; i < Object.keys(musics[key]).length; i++){539 musics[key][i].volume -= 0.2;540 }541 }542 //turn of mute and volume down buttons543 if (musics["music"][0].volume - 0.2 < 0 ){544 buttons["pauseMenu"][0].style.opacity = 0.3;545 buttons["pauseMenu"][0].style.cursor = "default";546 removeEVLButtons(buttons, "pauseMenu", 0, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);547 buttons["pauseMenu"][1].style.opacity = 0.3;548 buttons["pauseMenu"][1].style.cursor = "default";549 removeEVLButtons(buttons, "pauseMenu", 1, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);550 }551}552function somHighClickHandlerM(musics, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){553 console.log("+M"); 554 //place volume down and mute buttons again555 if (musics["music"][0].volume - 0.2 < 0 ){556 buttons["pauseMenu"][0].style.opacity = 1;557 addEVLButtons(buttons, "pauseMenu", 0, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);558 buttons["pauseMenu"][1].style.opacity = 1;559 addEVLButtons(buttons, "pauseMenu", 1, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);560 }561 for(let key in musics){562 for ( let i = 0; i < Object.keys(musics[key]).length; i++){563 musics[key][i].volume += 0.2;564 }565 }566 //turn off volume up button567 if (musics["music"][0].volume + 0.2 > 1){568 buttons["pauseMenu"][2].style.opacity = 0.3;569 buttons["pauseMenu"][2].style.cursor = "default";570 removeEVLButtons(buttons, "pauseMenu", 2, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);571 }572}573function muteClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){ 574 for(let key in sounds){575 for ( let i = 0; i < Object.keys(sounds[key]).length; i++){576 sounds[key][i].volume = 0;577 }578 }579 buttons["pauseMenu"][3].style.opacity = 0.3;580 buttons["pauseMenu"][3].style.cursor = "default";581 removeEVLButtons(buttons, "pauseMenu", 3, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);582 buttons["pauseMenu"][4].style.opacity = 0.3;583 buttons["pauseMenu"][4].style.cursor = "default";584 removeEVLButtons(buttons, "pauseMenu", 4, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);585 //sound goes from 1 to 0586 buttons["pauseMenu"][5].style.opacity = 1;587 addEVLButtons(buttons, "pauseMenu", 5, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);588}589function somLowClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){590 console.log("-S"); 591 592 //place volume up button again593 if (sounds["buttons"][0].volume + 0.2 > 1){594 buttons["pauseMenu"][5].style.opacity = 1;595 addEVLButtons(buttons, "pauseMenu", 5, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);596 }597 for(let key in sounds){598 for ( let i = 0; i < Object.keys(sounds[key]).length; i++){599 sounds[key][i].volume -= 0.2;600 }601 }602 //turn of mute and volume down buttons603 if (sounds["buttons"][0].volume - 0.2 < 0 ){604 buttons["pauseMenu"][4].style.opacity = 0.3;605 buttons["pauseMenu"][4].style.cursor = "default";606 removeEVLButtons(buttons, "pauseMenu", 4, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);607 buttons["pauseMenu"][3].style.opacity = 0.3;608 buttons["pauseMenu"][3].style.cursor = "default";609 removeEVLButtons(buttons, "pauseMenu", 3, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);610 }611}612function somHighClickHandlerS(sounds, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler){613 //place mute and volume down buttons again614 if (sounds["buttons"][0].volume - 0.2 < 0 ){615 buttons["pauseMenu"][3].style.opacity = 1;616 addEVLButtons(buttons, "pauseMenu", 3, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);617 buttons["pauseMenu"][4].style.opacity = 1;618 addEVLButtons(buttons, "pauseMenu", 4, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);619 }620 for(let key in sounds){621 for ( let i = 0; i < Object.keys(sounds[key]).length; i++){622 sounds[key][i].volume += 0.2;623 }624 }625 //turn off volume up button626 if (sounds["buttons"][0].volume + 0.2 > 1){627 buttons["pauseMenu"][5].style.opacity = 0.3;628 buttons["pauseMenu"][5].style.cursor = "default";629 removeEVLButtons(buttons, "pauseMenu", 5, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);630 }631}632function leaveDoGameClickHandler(auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux){633 //var text = document.getElementById("textPop");634 var text = domAux["textPop"];635 text.innerHTML = "Quere voltar ao menu principal??"636 buttons["popUpMenu"][0].style.display = "block";637 buttons["popUpMenu"][1].style.display = "none";638 buttons["popUpMenu"][2].style.display = "block";639 640 menus["popUpMenu"].style.display = "block";641 642 menus["popUpMenu"].style.zIndex = 4;643 //add listeners644 /*for (var i = 0 ; i < buttons["popUpMenu"].length; i++){645 addEVLButtons(buttons, "popUpMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler); 646 buttons["popUpMenu"][i].style.opacity = 1;647 }*/648 //REMOVE BUTTONS EVENTLISTENNERS649 //remove button ev listener that were left650 //doesn't change opacity so we know which have to get the ev listeners back651 for (var i = 0 ; i < buttons["pauseMenu"].length; i++){652 if (buttons["pauseMenu"][i].style.opacity == 1 || i == 6){653 removeEVLButtons(buttons, "pauseMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);654 }655 }656 buttons["pauseMenu"][6].style.opacity = 0.3;657}658//START------659function startClickHandler(ev, menus, auxMisc){660 menus["startMenu"].style.display = "";661 menus["loginRegMenu"].style.display = "block";662 auxMisc["currentMenu"] = "loginRegMenu";663 auxMisc["oldMenu"] = "startMenu";664}665//LOGIN REG------666function loginClickHandler(menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux, player){667 //var name = document.getElementById("name").value;668 var name = domAux["name"].value;669 //name doesn't exist -> PopUp670 if(checkCookie(name) == false){671 672 //var text = document.getElementById("textPop");673 var text = domAux["textPop"];674 text.innerHTML = "There isn't an account with that username."675 buttons["popUpMenu"][0].style.display = "none";676 buttons["popUpMenu"][1].style.display = "block";677 buttons["popUpMenu"][2].style.display = "none";678 679 menus["popUpMenu"].style.display = "block";680 //REMOVE BUTTONS EVENTLISTENNERS681 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){682 removeEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);683 buttons["loginRegMenu"][i].style.opacity = 1;684 }685 }else{686 player.name = name;687 player.getCookie();688 login(name, menus, auxMisc, musics, body, buttons, domAux, player);689 }690 691}692function signUpClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux, player){693 694 //var name = document.getElementById("name").value;695 var name = domAux["name"].value;696 //invalid name697 if( name.indexOf("Level") != -1 ||698 name.indexOf("Campain") != -1 ||699 name.indexOf("Endless") != -1 ||700 name.indexOf("Spaceships") != -1 ||701 name.indexOf("Tutorial") != -1 ||702 name.indexOf(" ") != -1 ||703 name == ""){704 //var text = document.getElementById("textPop");705 var text = domAux["textPop"];706 text.innerHTML = "Invalid Username. Keep in mind your name can't be empty, contain spaces or the words: \"Level\", \"Campain\", \"Endless\", \"Spaceships\" and \"Tutorial\"";707 buttons["popUpMenu"][0].style.display = "none";708 buttons["popUpMenu"][1].style.display = "block";709 buttons["popUpMenu"][2].style.display = "none";710 711 menus["popUpMenu"].style.display = "block";712 //REMOVE BUTTONS EVENTLISTENNERS713 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){714 removeEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);715 buttons["loginRegMenu"][i].style.opacity = 1;716 }717 //username already exists -> PopUp718 }else if(checkCookie(name) == true){719 //var text = document.getElementById("textPop");720 var text = domAux["textPop"];721 text.innerHTML = "This username has saved progress. Are you sure you want to erase it?"722 buttons["popUpMenu"][0].style.display = "block";723 buttons["popUpMenu"][1].style.display = "none";724 buttons["popUpMenu"][2].style.display = "block";725 726 menus["popUpMenu"].style.display = "block";727 //REMOVE BUTTONS EVENTLISTENNERS728 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){729 removeEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);730 buttons["loginRegMenu"][i].style.opacity = 1;731 }732 }else{733 player.createPlayer(name);734 login(name, menus, auxMisc, musics, body, buttons, domAux, player);735 }736}737//POP UP------738function yesClickHandler(ev, menus, auxMisc, musics, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler, body, domAux, player){739 menus["popUpMenu"].style.display = "";740 menus["popUpMenu"].style.zIndex = 1;741 //if the popup is on Log Reg Menu742 if (auxMisc["currentMenu"] == "loginRegMenu"){743 744 //var name = document.getElementById("name").value;745 var name = domAux["name"].value;746 player.createPlayer(name);747 login(name, menus, auxMisc, musics, body, buttons, domAux, player);748 //Reset Listeners749 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){750 addEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);751 }752 }753 //if the popup appears during a game754 else{755 /*buttons["pauseMenu"][6].style.opacity = 1;756 for (var i = 0 ; i < buttons["pauseMenu"].length; i++){757 if (buttons["pauseMenu"][i].style.opacity == 1 ){758 addEVLButtons(buttons, "pauseMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);759 }760 }761 //Code to get back to the menu (Henrique)762 763 */764 }765}766function okClickHandler(ev, menus, auxMisc, buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler){767 menus["popUpMenu"].style.display = ""; 768 menus["popUpMenu"].style.zIndex = 1;769 //if the PopUpMenu has style.display = "block" and the user came from a game770 //this means he unlocked something ingame.771 if(auxMisc["oldMenu"] == "algumGame;_;"){772 for(let key in buttons){773 if(key != "pauseMenu" || key != "popUpMenu" ){774 for (var i = 0; i < Object.keys(buttons[key]).length; i++){775 addEVLButtons(buttons, key, i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);776 }777 }778 }779 //else if (auxMisc["currentMenu"] == "loginRegMenu" || auxMisc["currentMenu"] == "mainMenu"){780 }//if the PopUpMemu is on the Log Reg Menu or MainMenu781 else{782 //Reset Listeners783 for (var i = 0 ; i < buttons[auxMisc["currentMenu"]].length; i++){784 addEVLButtons(buttons, auxMisc["currentMenu"], i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);785 }786 }787}788function noClickHandler(ev, menus, auxMisc,buttons, auxClickHandler,auxMouseInHandler,auxMouseOutHandler){789 menus["popUpMenu"].style.display = ""; 790 menus["popUpMenu"].style.zIndex = 1;791 //if the PopUpMemu is on the Log Reg Menu792 if (auxMisc["currentMenu"] == "loginRegMenu"){793 //Reset listeners794 for (var i = 0 ; i < buttons["loginRegMenu"].length; i++){795 addEVLButtons(buttons, "loginRegMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);796 }797 //if the PopUpMemu appears while ingame (Henrique)798 }else{799 /*buttons["pauseMenu"][6].style.opacity = 1;800 for (var i = 0 ; i < buttons["pauseMenu"].length; i++){801 if (buttons["pauseMenu"][i].style.opacity == 1 ){802 addEVLButtons(buttons, "pauseMenu", i, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);803 }804 }*/805 }806}807//MAIN MENU------808function campainClickHandler(ev, auxMisc, menus, domAux){809 menus["mainMenu"].style.display = "";810 menus["levelMenu"].style.display = "block";811 auxMisc["currentMenu"] = "levelMenu";812 auxMisc["oldMenu"] = "mainMenu";813 var name = auxMisc["playerAtual"];814 console.log(name);815 //document.getElementById("playerLevel").innerHTML = name;816 domAux["playerLevel"].innerHTM = name;817}818function endlessClickHandler(ev, auxMisc, menus, buttons, body, spaceships,imgs){819 body.bgColor = "#0a131f";820 menus["mainMenu"].style.display = "";821 menus["chooseSpaceshipMenu"].style.display = "block";822 auxMisc["currentMenu"] = "chooseSpaceshipMenu";823 auxMisc["oldMenu"] = "mainMenu";824 auxMisc["gamemode"] = "endless";825 putCorrectSpaceships(auxMisc, menus, buttons, spaceships,imgs);826}827function playEndlessClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){828 body.bgColor = "black";829 menus["chooseSpaceshipMenu"].style.display = "";830 menus["canvasFigure"].style.display = "block";831 832 auxMisc["currentMenu"] = "endless";833 auxMisc["oldMenu"] = "chooseSpaceshipMenu";834 removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);835 new Game(auxMisc, menus, buttons, imgs, sounds, musics, body, domAux, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, -1, player);836}837function closesGameClickHandler(ev, auxMisc, sounds, musics, menus, body){838 menus["mainMenu"].style.display = "";839 firstMenu(menus, auxMisc, musics, body);840}841function creditsClickHandler(ev, menus, auxMisc, domAux){842 menus["mainMenu"].style.display = "";843 menus["creditsMenu"].style.display = "block";844 auxMisc["currentMenu"] = "creditsMenu";845 auxMisc["oldMenu"] = "mainMenu";846 var name = auxMisc["playerAtual"];847 //document.getElementById("playerCredits").innerHTML = name;848 domAux["playerCredits"].innerHTML = name;849}850function helpClickHandler(ev, menus, auxMisc, body){851 body.bgColor = "#0a131f";852 menus["mainMenu"].style.display = "";853 menus["helpMenu"].style.display = "block";854 auxMisc["currentMenu"] = "helpMenu";855 auxMisc["oldMenu"] = "mainMenu";856}857function leaderBoardClickHandler(ev, menus, auxMisc, body, domAux){858 body.bgColor = "#0a131f";859 menus["mainMenu"].style.display = "";860 menus["leaderBoard"].style.display = "block";861 auxMisc["currentMenu"] = "leaderBoard";862 auxMisc["oldMenu"] = "mainMenu";863 var name = auxMisc["playerAtual"];864 //document.getElementById("playerLeaderBoard").innerHTML = name;865 domAux["playerLeaderBoard"].innerHTML = name;866}867function controlsClickHandler(ev, menus, auxMisc, body){868 body.bgColor = "#0a131f";869 menus["mainMenu"].style.display = "";870 menus["controlsMenu"].style.display = "block";871 auxMisc["currentMenu"] = "controlsMenu";872 auxMisc["oldMenu"] = "mainMenu";873}874//NIVEL MENU-------875function levelClickHandler(ev, auxMisc, menus, buttons, body, level, spaceships, imgs){876 body.bgColor = "#0a131f";877 menus["levelMenu"].style.display = "";878 menus["chooseSpaceshipMenu"].style.display = "block";879 auxMisc["currentMenu"] = "chooseSpaceshipMenu";880 auxMisc["oldMenu"] = "levelMenu";881 auxMisc["gamemode"] = "level_" + level;882 putCorrectSpaceships(auxMisc, menus, buttons, spaceships, imgs);883}884function speedrunClickHandler(ev, auxMisc, menus, buttons, body, spaceships, imgs){885 body.bgColor = "#0a131f";886 menus["levelMenu"].style.display = "";887 menus["chooseSpaceshipMenu"].style.display = "block";888 auxMisc["currentMenu"] = "chooseSpaceshipMenu";889 auxMisc["oldMenu"] = "levelMenu";890 auxMisc["gamemode"] = "speedrun";891 putCorrectSpaceships(auxMisc, menus, buttons, spaceships, imgs);892}893function levelMenuBack(ev,menus,auxMisc){894 menus["levelMenu"].style.display = "";895 menus["mainMenu"].style.display = "block";896 auxMisc["currentMenu"] = "mainMenu";897 auxMisc["oldMenu"] = "levelMenu";898}899//CHOOSE SPACESHIP MENU-------900function playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){901 //hasn't seen the controls menu902 if(auxMisc["cookieStore"]["Tutorial"][0] == "0"){903 //appears Controls904 body.bgColor = "#0a131f";905 menus["chooseSpaceshipMenu"].style.display = "";906 menus["controlsMenu"].style.display = "block";907 908 auxMisc["currentMenu"] = "controlsMenu";909 auxMisc["oldMenu"] = "chooseSpaceshipMenu";910 //checks if the user knows the Help menu911 if(auxMisc["cookieStore"]["Tutorial"][1] == "0" ){912 //buttonNext913 buttons["controlsMenu"][1].style.display = "block";914 }else{915 //buttonPlay916 buttons["controlsMenu"][2].style.display = "block";917 }918 //hasn't seen the help menu <=> Tutorial[1] == "0"919 }else if (auxMisc["cookieStore"]["Tutorial"] == "10"){920 921 //appears Help922 body.bgColor = "#0a131f";923 menus["chooseSpaceshipMenu"].style.display = "";924 menus["helpMenu"].style.display = "block";925 926 auxMisc["oldMenu"] = "chooseSpaceshipMenu";927 auxMisc["currentMenu"] = "helpMenu";928 //appears buttons 929 buttons["helpMenu"][1].style.display = "block";930 931 //user knows controls and help menus932 }else if (auxMisc["cookieStore"]["Tutorial"] == "11"){933 var gamemode = auxMisc["gamemode"].split("_")[0]; 934 buttons["helpMenu"][1].style.display = "";935 buttons["controlsMenu"][1].style.display = "";936 buttons["controlsMenu"][2].style.display = "";937 if ( gamemode== "level"){938 playLevelClickHandler(ev, auxMisc, menus, buttons, imgs, sounds,musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, parseInt(auxMisc["gamemode"].split("_")[1]), domAux, player);939 }940 else if (gamemode == "speedrun"){941 playSpeedrunClickHandler(ev, auxMisc, menus, buttons, imgs, sounds,musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);942 }943 else if (gamemode == "endless"){944 playEndlessClickHandler(ev, auxMisc, menus, buttons, imgs, sounds,musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);945 }946 }947}948function playLevelClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, level, domAux, player){949 body.bgColor = "black";950 menus["chooseSpaceshipMenu"].style.display = "";951 menus["canvasFigure"].style.display = "block";952 953 auxMisc["currentMenu"] = "level" + level + "Menu";954 auxMisc["oldMenu"] = "chooseSpaceshipMenu";955 removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);956 new Game(auxMisc, menus, buttons, imgs, sounds, musics, body, domAux, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, level, player);957}958function playSpeedrunClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){959 body.bgColor = "black";960 menus["chooseSpaceshipMenu"].style.display = "";961 menus["canvasFigure"].style.display = "block";962 963 auxMisc["currentMenu"] = "speedrun";964 auxMisc["oldMenu"] = "chooseSpaceshipMenu";965 removeEventListeners(buttons, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler);966 new Game(auxMisc, menus, buttons, imgs, sounds, musics, body, domAux, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, 0, player);967}968function rightClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs){969 //var data = player.getCookie(auxMisc["playerAtual"]);970 var spaceshipsUser = auxMisc["cookieStore"]["Spaceships"];971 var spaceshipAntiga = auxMisc["currentSpaceship"];972 auxMisc["currentSpaceship"] = myMod(auxMisc["currentSpaceship"] -1, spaceshipsUser.length); 973 var appears_left = myMod(auxMisc["currentSpaceship"] - 1,spaceshipsUser.length);974 var right = spaceshipAntiga;975 var leave_right = myMod(auxMisc["currentSpaceship"] + 2, spaceshipsUser.length);976 auxChangeSpaceships(menus, buttons,spaceships,imgs, spaceshipsUser, spaceshipAntiga, appears_left, auxMisc["currentSpaceship"], right, leave_right);977}978function leftClickHandler(ev, auxMisc, menus, buttons, spaceships, imgs){979 //var data = player.getCookie(auxMisc["playerAtual"]);980 var spaceshipsUser = auxMisc["cookieStore"]["Spaceships"];981 982 var spaceshipAntiga = auxMisc["currentSpaceship"];983 auxMisc["currentSpaceship"] = myMod(auxMisc["currentSpaceship"] + 1, spaceshipsUser.length); 984 var leave_left = myMod(auxMisc["currentSpaceship"] - 2,spaceshipsUser.length);985 var left = spaceshipAntiga;986 var appears_right = myMod(auxMisc["currentSpaceship"] + 1, spaceshipsUser.length);987 auxChangeSpaceships(menus, buttons,spaceships,imgs, spaceshipsUser, spaceshipAntiga, left, auxMisc["currentSpaceship"], appears_right, leave_left);988}989function chooseSpaceshipsMenuBack(ev, menus, auxMisc, body){990 menus["chooseSpaceshipMenu"].style.display = "";991 body.bgColor = "#00081d";992 if( auxMisc["gamemode"] != "endless" ){993 menus["levelMenu"].style.display = "block";994 auxMisc["currentMenu"] = "levelMenu";995 }else{996 menus["mainMenu"].style.display = "block";997 998 auxMisc["currentMenu"] = "mainMenu";999 }1000 auxMisc["oldMenu"] = "chooseSpaceshipMenu";1001}1002//LEADERBOARD------1003function leaderBoardBackClickHandler(ev, menus, auxMisc, body){1004 body.bgColor = "#00081d";1005 menus["leaderBoard"].style.display = "";1006 menus["mainMenu"].style.display = "block";1007 auxMisc["currentMenu"] = "mainMenu";1008 auxMisc["oldMenu"] = "leaderBoard";1009}1010//CREDITOS MENU------1011function creditsBackClickHandler(ev, menus, auxMisc){1012 menus["creditsMenu"].style.display = "";1013 menus["mainMenu"].style.display = "block";1014 1015 auxMisc["currentMenu"] = "mainMenu";1016 auxMisc["oldMenu"] = "creditsMenu";1017}1018//CONTROLOS MENU -----1019function controlsBackClickHandler(ev, menus, auxMisc,body, buttons, player){1020 1021 menus["controlsMenu"].style.display = "";1022 buttons["controlsMenu"][1].style.display = "";1023 buttons["controlsMenu"][2].style.display = "";1024 //user already saw the Controls menu1025 auxMisc["cookieStore"]["Tutorial"] = "1"+auxMisc["cookieStore"]["Tutorial"][1];1026 player.updateCoockiesTutorial(auxMisc,"1"+auxMisc["cookieStore"]["Tutorial"][1]);1027 if(auxMisc["oldMenu"] == "mainMenu"){1028 body.bgColor = "#00081d";1029 menus["mainMenu"].style.display = "block";1030 auxMisc["currentMenu"] = "mainMenu";1031 auxMisc["oldMenu"] = "controlsMenu";1032 }else{1033 body.bgColor = "#0a131f";1034 menus["chooseSpaceshipMenu"].style.display = "block";1035 auxMisc["currentMenu"] = "chooseSpaceshipMenu";1036 auxMisc["oldMenu"] = "controlsMenu";1037 1038 buttons["helpMenu"][1].style.display = "";1039 }1040}1041function controlsNextClickHandler(ev, menus, auxMisc, body, buttons, player){1042 body.bgColor = "#0a131f";1043 menus["controlsMenu"].style.display = "";1044 menus["helpMenu"].style.display = "block";1045 auxMisc["currentMenu"] = "helpMenu";1046 auxMisc["oldMenu"] = "controlsMenu";1047 auxMisc["cookieStore"]["Tutorial"] = "1"+auxMisc["cookieStore"]["Tutorial"][1] ;1048 player.updateCoockiesTutorial(auxMisc,"1"+auxMisc["cookieStore"]["Tutorial"][1]);1049 buttons["helpMenu"][1].style.display = "block";1050}1051function controlsPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){1052 menus["controlsMenu"].style.display = "";1053 1054 //user already saw the Controls menu1055 auxMisc["cookieStore"]["Tutorial"] = "1"+auxMisc["cookieStore"]["Tutorial"][1] ;1056 player.updateCoockiesTutorial(auxMisc,"1"+auxMisc["cookieStore"]["Tutorial"][1]);1057 playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);1058}1059//HELP MENU------1060function helpBackClickHandler(ev, menus, auxMisc, body, player){1061 //goes to the old menu1062 //if Tutorial[1] == 1 goes to mainMenu;1063 //if Tutorial[1] == 0 goes to controls or chooseSpaceshipsMenu1064 if(auxMisc["oldMenu"] == "mainMenu"){1065 body.bgColor = "#00081d";1066 }else{1067 body.bgColor = "#0a131f";1068 }1069 menus["helpMenu"].style.display = "";1070 menus[auxMisc["oldMenu"]].style.display = "block";1071 auxMisc["currentMenu"] = auxMisc["oldMenu"];1072 auxMisc["oldMenu"] = "helpMenu";1073 1074 //user already saw the Help menu1075 auxMisc["cookieStore"]["Tutorial"] = auxMisc["cookieStore"]["Tutorial"][0]+"1" ;1076 player.updateCoockiesTutorial(auxMisc, auxMisc["cookieStore"]["Tutorial"][0]+"1");1077}1078function helpPlayClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player){1079 menus["helpMenu"].style.display = "";1080 1081 //user already saw the Help menu1082 auxMisc["cookieStore"]["Tutorial"] = auxMisc["cookieStore"]["Tutorial"][0]+"1" ;1083 player.updateCoockiesTutorial(auxMisc, auxMisc["cookieStore"]["Tutorial"][0]+"1");1084 playClickHandler(ev, auxMisc, menus, buttons, imgs, sounds, musics, auxKeyDownHandler, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, body, domAux, player);1085}1086//Handlers ^^^^^^1087//Aux Functions vvvvvvvv1088function secret(ev, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player){1089 var unlockingSpaceship = 4;1090 //checks if he is on the mainMenu, if he still doesn't have the spaceship and if the popUp menu isn't open1091 if(auxMisc["currentMenu"] == "mainMenu" && menus["pauseMenu"].style.display == "" && auxMisc["cookieStore"]["Spaceships"][unlockingSpaceship] != "1" && menus["popUpMenu"].style.display == ""){1092 auxMisc["secretProgress"] += ev.code.substring(3);1093 if(auxMisc["secretPress"] == auxMisc["secretProgress"]){1094 unlockSpaceship(unlockingSpaceship, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player); 1095 }1096 }1097}1098function unlockSpaceship(unlockingSpaceship, auxMisc, menus, buttons, auxClickHandler, auxMouseInHandler, auxMouseOutHandler, domAux, player){...

Full Screen

Full Screen

jquery.mockjax.js

Source:jquery.mockjax.js Github

copy

Full Screen

1/*!2 * MockJax - jQuery Plugin to Mock Ajax requests3 *4 * Version: 1.6.15 * Released:6 * Home: https://github.com/jakerella/jquery-mockjax7 * Author: Jonathan Sharp (http://jdsharp.com)8 * License: MIT,GPL9 *10 * Copyright (c) 2014 appendTo, Jordan Kasper11 * NOTE: This repository was taken over by Jordan Kasper (@jakerella) October, 201412 * 13 * Dual licensed under the MIT or GPL licenses.14 * http://opensource.org/licenses/MIT OR http://www.gnu.org/licenses/gpl-2.0.html15 */16(function($) {17 var _ajax = $.ajax,18 mockHandlers = [],19 mockedAjaxCalls = [],20 unmockedAjaxCalls = [],21 CALLBACK_REGEX = /=\?(&|$)/,22 jsc = (new Date()).getTime();23 // Parse the given XML string.24 function parseXML(xml) {25 if ( window.DOMParser == undefined && window.ActiveXObject ) {26 DOMParser = function() { };27 DOMParser.prototype.parseFromString = function( xmlString ) {28 var doc = new ActiveXObject('Microsoft.XMLDOM');29 doc.async = 'false';30 doc.loadXML( xmlString );31 return doc;32 };33 }34 try {35 var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );36 if ( $.isXMLDoc( xmlDoc ) ) {37 var err = $('parsererror', xmlDoc);38 if ( err.length == 1 ) {39 throw new Error('Error: ' + $(xmlDoc).text() );40 }41 } else {42 throw new Error('Unable to parse XML');43 }44 return xmlDoc;45 } catch( e ) {46 var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );47 $(document).trigger('xmlParseError', [ msg ]);48 return undefined;49 }50 }51 // Check if the data field on the mock handler and the request match. This52 // can be used to restrict a mock handler to being used only when a certain53 // set of data is passed to it.54 function isMockDataEqual( mock, live ) {55 var identical = true;56 // Test for situations where the data is a querystring (not an object)57 if (typeof live === 'string') {58 // Querystring may be a regex59 return $.isFunction( mock.test ) ? mock.test(live) : mock == live;60 }61 $.each(mock, function(k) {62 if ( live[k] === undefined ) {63 identical = false;64 return identical;65 } else {66 if ( typeof live[k] === 'object' && live[k] !== null ) {67 if ( identical && $.isArray( live[k] ) ) {68 identical = $.isArray( mock[k] ) && live[k].length === mock[k].length;69 }70 identical = identical && isMockDataEqual(mock[k], live[k]);71 } else {72 if ( mock[k] && $.isFunction( mock[k].test ) ) {73 identical = identical && mock[k].test(live[k]);74 } else {75 identical = identical && ( mock[k] == live[k] );76 }77 }78 }79 });80 return identical;81 }82 // See if a mock handler property matches the default settings83 function isDefaultSetting(handler, property) {84 return handler[property] === $.mockjaxSettings[property];85 }86 // Check the given handler should mock the given request87 function getMockForRequest( handler, requestSettings ) {88 // If the mock was registered with a function, let the function decide if we89 // want to mock this request90 if ( $.isFunction(handler) ) {91 return handler( requestSettings );92 }93 // Inspect the URL of the request and check if the mock handler's url94 // matches the url for this ajax request95 if ( $.isFunction(handler.url.test) ) {96 // The user provided a regex for the url, test it97 if ( !handler.url.test( requestSettings.url ) ) {98 return null;99 }100 } else {101 // Look for a simple wildcard '*' or a direct URL match102 var star = handler.url.indexOf('*');103 if (handler.url !== requestSettings.url && star === -1 ||104 !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {105 return null;106 }107 }108 // Inspect the data submitted in the request (either POST body or GET query string)109 if ( handler.data ) {110 if ( ! requestSettings.data || !isMockDataEqual(handler.data, requestSettings.data) ) {111 // They're not identical, do not mock this request112 return null;113 }114 }115 // Inspect the request type116 if ( handler && handler.type &&117 handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) {118 // The request type doesn't match (GET vs. POST)119 return null;120 }121 return handler;122 }123 function parseResponseTimeOpt(responseTime) {124 if ($.isArray(responseTime)) {125 var min = responseTime[0];126 var max = responseTime[1];127 return (typeof min === 'number' && typeof max === 'number') ? Math.floor(Math.random() * (max - min)) + min : null;128 } else {129 return (typeof responseTime === 'number') ? responseTime: null;130 }131 }132 // Process the xhr objects send operation133 function _xhrSend(mockHandler, requestSettings, origSettings) {134 // This is a substitute for < 1.4 which lacks $.proxy135 var process = (function(that) {136 return function() {137 return (function() {138 // The request has returned139 this.status = mockHandler.status;140 this.statusText = mockHandler.statusText;141 this.readyState = 1;142 var finishRequest = function () {143 this.readyState = 4;144 var onReady;145 // Copy over our mock to our xhr object before passing control back to146 // jQuery's onreadystatechange callback147 if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {148 this.responseText = JSON.stringify(mockHandler.responseText);149 } else if ( requestSettings.dataType == 'xml' ) {150 if ( typeof mockHandler.responseXML == 'string' ) {151 this.responseXML = parseXML(mockHandler.responseXML);152 //in jQuery 1.9.1+, responseXML is processed differently and relies on responseText153 this.responseText = mockHandler.responseXML;154 } else {155 this.responseXML = mockHandler.responseXML;156 }157 } else if (typeof mockHandler.responseText === 'object' && mockHandler.responseText !== null) {158 // since jQuery 1.9 responseText type has to match contentType159 mockHandler.contentType = 'application/json';160 this.responseText = JSON.stringify(mockHandler.responseText);161 } else {162 this.responseText = mockHandler.responseText;163 }164 if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {165 this.status = mockHandler.status;166 }167 if( typeof mockHandler.statusText === "string") {168 this.statusText = mockHandler.statusText;169 }170 // jQuery 2.0 renamed onreadystatechange to onload171 onReady = this.onreadystatechange || this.onload;172 // jQuery < 1.4 doesn't have onreadystate change for xhr173 if ( $.isFunction( onReady ) ) {174 if( mockHandler.isTimeout) {175 this.status = -1;176 }177 onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );178 } else if ( mockHandler.isTimeout ) {179 // Fix for 1.3.2 timeout to keep success from firing.180 this.status = -1;181 }182 };183 // We have an executable function, call it to give184 // the mock handler a chance to update it's data185 if ( $.isFunction(mockHandler.response) ) {186 // Wait for it to finish187 if ( mockHandler.response.length === 2 ) {188 mockHandler.response(origSettings, function () {189 finishRequest.call(that);190 });191 return;192 } else {193 mockHandler.response(origSettings);194 }195 }196 finishRequest.call(that);197 }).apply(that);198 };199 })(this);200 if ( mockHandler.proxy ) {201 // We're proxying this request and loading in an external file instead202 _ajax({203 global: false,204 url: mockHandler.proxy,205 type: mockHandler.proxyType,206 data: mockHandler.data,207 dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,208 complete: function(xhr) {209 mockHandler.responseXML = xhr.responseXML;210 mockHandler.responseText = xhr.responseText;211 // Don't override the handler status/statusText if it's specified by the config212 if (isDefaultSetting(mockHandler, 'status')) {213 mockHandler.status = xhr.status;214 }215 if (isDefaultSetting(mockHandler, 'statusText')) {216 mockHandler.statusText = xhr.statusText;217 }218 this.responseTimer = setTimeout(process, parseResponseTimeOpt(mockHandler.responseTime) || 0);219 }220 });221 } else {222 // type == 'POST' || 'GET' || 'DELETE'223 if ( requestSettings.async === false ) {224 // TODO: Blocking delay225 process();226 } else {227 this.responseTimer = setTimeout(process, parseResponseTimeOpt(mockHandler.responseTime) || 50);228 }229 }230 }231 // Construct a mocked XHR Object232 function xhr(mockHandler, requestSettings, origSettings, origHandler) {233 // Extend with our default mockjax settings234 mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);235 if (typeof mockHandler.headers === 'undefined') {236 mockHandler.headers = {};237 }238 if (typeof requestSettings.headers === 'undefined') {239 requestSettings.headers = {};240 }241 if ( mockHandler.contentType ) {242 mockHandler.headers['content-type'] = mockHandler.contentType;243 }244 return {245 status: mockHandler.status,246 statusText: mockHandler.statusText,247 readyState: 1,248 open: function() { },249 send: function() {250 origHandler.fired = true;251 _xhrSend.call(this, mockHandler, requestSettings, origSettings);252 },253 abort: function() {254 clearTimeout(this.responseTimer);255 },256 setRequestHeader: function(header, value) {257 requestSettings.headers[header] = value;258 },259 getResponseHeader: function(header) {260 // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery261 if ( mockHandler.headers && mockHandler.headers[header] ) {262 // Return arbitrary headers263 return mockHandler.headers[header];264 } else if ( header.toLowerCase() == 'last-modified' ) {265 return mockHandler.lastModified || (new Date()).toString();266 } else if ( header.toLowerCase() == 'etag' ) {267 return mockHandler.etag || '';268 } else if ( header.toLowerCase() == 'content-type' ) {269 return mockHandler.contentType || 'text/plain';270 }271 },272 getAllResponseHeaders: function() {273 var headers = '';274 // since jQuery 1.9 responseText type has to match contentType275 if (mockHandler.contentType) {276 mockHandler.headers['Content-Type'] = mockHandler.contentType;277 }278 $.each(mockHandler.headers, function(k, v) {279 headers += k + ': ' + v + "\n";280 });281 return headers;282 }283 };284 }285 // Process a JSONP mock request.286 function processJsonpMock( requestSettings, mockHandler, origSettings ) {287 // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here288 // because there isn't an easy hook for the cross domain script tag of jsonp289 processJsonpUrl( requestSettings );290 requestSettings.dataType = "json";291 if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {292 createJsonpCallback(requestSettings, mockHandler, origSettings);293 // We need to make sure294 // that a JSONP style response is executed properly295 var rurl = /^(\w+:)?\/\/([^\/?#]+)/,296 parts = rurl.exec( requestSettings.url ),297 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);298 requestSettings.dataType = "script";299 if(requestSettings.type.toUpperCase() === "GET" && remote ) {300 var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );301 // Check if we are supposed to return a Deferred back to the mock call, or just302 // signal success303 if(newMockReturn) {304 return newMockReturn;305 } else {306 return true;307 }308 }309 }310 return null;311 }312 // Append the required callback parameter to the end of the request URL, for a JSONP request313 function processJsonpUrl( requestSettings ) {314 if ( requestSettings.type.toUpperCase() === "GET" ) {315 if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {316 requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +317 (requestSettings.jsonp || "callback") + "=?";318 }319 } else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {320 requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";321 }322 }323 // Process a JSONP request by evaluating the mocked response text324 function processJsonpRequest( requestSettings, mockHandler, origSettings ) {325 // Synthesize the mock request for adding a script tag326 var callbackContext = origSettings && origSettings.context || requestSettings,327 newMock = null;328 // If the response handler on the moock is a function, call it329 if ( mockHandler.response && $.isFunction(mockHandler.response) ) {330 mockHandler.response(origSettings);331 } else {332 // Evaluate the responseText javascript in a global context333 if( typeof mockHandler.responseText === 'object' ) {334 $.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');335 } else {336 $.globalEval( '(' + mockHandler.responseText + ')');337 }338 }339 // Successful response340 setTimeout(function() {341 jsonpSuccess( requestSettings, callbackContext, mockHandler );342 jsonpComplete( requestSettings, callbackContext, mockHandler );343 }, parseResponseTimeOpt(mockHandler.responseTime) || 0);344 // If we are running under jQuery 1.5+, return a deferred object345 if($.Deferred){346 newMock = new $.Deferred();347 if(typeof mockHandler.responseText == "object"){348 newMock.resolveWith( callbackContext, [mockHandler.responseText] );349 }350 else{351 newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );352 }353 }354 return newMock;355 }356 // Create the required JSONP callback function for the request357 function createJsonpCallback( requestSettings, mockHandler, origSettings ) {358 var callbackContext = origSettings && origSettings.context || requestSettings;359 var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);360 // Replace the =? sequence both in the query string and the data361 if ( requestSettings.data ) {362 requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");363 }364 requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");365 // Handle JSONP-style loading366 window[ jsonp ] = window[ jsonp ] || function( tmp ) {367 data = tmp;368 jsonpSuccess( requestSettings, callbackContext, mockHandler );369 jsonpComplete( requestSettings, callbackContext, mockHandler );370 // Garbage collect371 window[ jsonp ] = undefined;372 try {373 delete window[ jsonp ];374 } catch(e) {}375 if ( head ) {376 head.removeChild( script );377 }378 };379 }380 // The JSONP request was successful381 function jsonpSuccess(requestSettings, callbackContext, mockHandler) {382 // If a local callback was specified, fire it and pass it the data383 if ( requestSettings.success ) {384 requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );385 }386 // Fire the global callback387 if ( requestSettings.global ) {388 (requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxSuccess", [{}, requestSettings]);389 }390 }391 // The JSONP request was completed392 function jsonpComplete(requestSettings, callbackContext) {393 // Process result394 if ( requestSettings.complete ) {395 requestSettings.complete.call( callbackContext, {} , status );396 }397 // The request was completed398 if ( requestSettings.global ) {399 (requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxComplete", [{}, requestSettings]);400 }401 // Handle the global AJAX counter402 if ( requestSettings.global && ! --$.active ) {403 $.event.trigger( "ajaxStop" );404 }405 }406 // The core $.ajax replacement.407 function handleAjax( url, origSettings ) {408 var mockRequest, requestSettings, mockHandler, overrideCallback;409 // If url is an object, simulate pre-1.5 signature410 if ( typeof url === "object" ) {411 origSettings = url;412 url = undefined;413 } else {414 // work around to support 1.5 signature415 origSettings = origSettings || {};416 origSettings.url = url;417 }418 // Extend the original settings for the request419 requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);420 // Generic function to override callback methods for use with421 // callback options (onAfterSuccess, onAfterError, onAfterComplete)422 overrideCallback = function(action, mockHandler) {423 var origHandler = origSettings[action.toLowerCase()];424 return function() {425 if ( $.isFunction(origHandler) ) {426 origHandler.apply(this, [].slice.call(arguments));427 }428 mockHandler['onAfter' + action]();429 };430 };431 // Iterate over our mock handlers (in registration order) until we find432 // one that is willing to intercept the request433 for(var k = 0; k < mockHandlers.length; k++) {434 if ( !mockHandlers[k] ) {435 continue;436 }437 mockHandler = getMockForRequest( mockHandlers[k], requestSettings );438 if(!mockHandler) {439 // No valid mock found for this request440 continue;441 }442 mockedAjaxCalls.push(requestSettings);443 // If logging is enabled, log the mock to the console444 $.mockjaxSettings.log( mockHandler, requestSettings );445 if ( requestSettings.dataType && requestSettings.dataType.toUpperCase() === 'JSONP' ) {446 if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {447 // This mock will handle the JSONP request448 return mockRequest;449 }450 }451 // Removed to fix #54 - keep the mocking data object intact452 //mockHandler.data = requestSettings.data;453 mockHandler.cache = requestSettings.cache;454 mockHandler.timeout = requestSettings.timeout;455 mockHandler.global = requestSettings.global;456 // In the case of a timeout, we just need to ensure457 // an actual jQuery timeout (That is, our reponse won't)458 // return faster than the timeout setting.459 if ( mockHandler.isTimeout ) {460 if ( mockHandler.responseTime > 1 ) {461 origSettings.timeout = mockHandler.responseTime - 1;462 } else {463 mockHandler.responseTime = 2;464 origSettings.timeout = 1;465 }466 mockHandler.isTimeout = false;467 }468 // Set up onAfter[X] callback functions469 if ( $.isFunction( mockHandler.onAfterSuccess ) ) {470 origSettings.success = overrideCallback('Success', mockHandler);471 }472 if ( $.isFunction( mockHandler.onAfterError ) ) {473 origSettings.error = overrideCallback('Error', mockHandler);474 }475 if ( $.isFunction( mockHandler.onAfterComplete ) ) {476 origSettings.complete = overrideCallback('Complete', mockHandler);477 }478 copyUrlParameters(mockHandler, origSettings);479 (function(mockHandler, requestSettings, origSettings, origHandler) {480 mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {481 // Mock the XHR object482 xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }483 }));484 })(mockHandler, requestSettings, origSettings, mockHandlers[k]);485 return mockRequest;486 }487 // We don't have a mock request488 unmockedAjaxCalls.push(origSettings);489 if($.mockjaxSettings.throwUnmocked === true) {490 throw new Error('AJAX not mocked: ' + origSettings.url);491 }492 else { // trigger a normal request493 return _ajax.apply($, [origSettings]);494 }495 }496 /**497 * Copies URL parameter values if they were captured by a regular expression498 * @param {Object} mockHandler499 * @param {Object} origSettings500 */501 function copyUrlParameters(mockHandler, origSettings) {502 //parameters aren't captured if the URL isn't a RegExp503 if (!(mockHandler.url instanceof RegExp)) {504 return;505 }506 //if no URL params were defined on the handler, don't attempt a capture507 if (!mockHandler.hasOwnProperty('urlParams')) {508 return;509 }510 var captures = mockHandler.url.exec(origSettings.url);511 //the whole RegExp match is always the first value in the capture results512 if (captures.length === 1) {513 return;514 }515 captures.shift();516 //use handler params as keys and capture resuts as values517 var i = 0,518 capturesLength = captures.length,519 paramsLength = mockHandler.urlParams.length,520 //in case the number of params specified is less than actual captures521 maxIterations = Math.min(capturesLength, paramsLength),522 paramValues = {};523 for (i; i < maxIterations; i++) {524 var key = mockHandler.urlParams[i];525 paramValues[key] = captures[i];526 }527 origSettings.urlParams = paramValues;528 }529 // Public530 $.extend({531 ajax: handleAjax532 });533 $.mockjaxSettings = {534 //url: null,535 //type: 'GET',536 log: function( mockHandler, requestSettings ) {537 if ( mockHandler.logging === false ||538 ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {539 return;540 }541 if ( window.console && console.log ) {542 var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;543 var request = $.extend({}, requestSettings);544 if (typeof console.log === 'function') {545 console.log(message, request);546 } else {547 try {548 console.log( message + ' ' + JSON.stringify(request) );549 } catch (e) {550 console.log(message);551 }552 }553 }554 },555 logging: true,556 status: 200,557 statusText: "OK",558 responseTime: 500,559 isTimeout: false,560 throwUnmocked: false,561 contentType: 'text/plain',562 response: '',563 responseText: '',564 responseXML: '',565 proxy: '',566 proxyType: 'GET',567 lastModified: null,568 etag: '',569 headers: {570 etag: 'IJF@H#@923uf8023hFO@I#H#',571 'content-type' : 'text/plain'572 }573 };574 $.mockjax = function(settings) {575 var i = mockHandlers.length;576 mockHandlers[i] = settings;577 return i;578 };579 $.mockjax.clear = function(i) {580 if ( arguments.length == 1 ) {581 mockHandlers[i] = null;582 } else {583 mockHandlers = [];584 }585 mockedAjaxCalls = [];586 unmockedAjaxCalls = [];587 };588 // support older, deprecated version589 $.mockjaxClear = function(i) {590 window.console && window.console.warn && window.console.warn( 'DEPRECATED: The $.mockjaxClear() method has been deprecated in 1.6.0. Please use $.mockjax.clear() as the older function will be removed soon!' );591 $.mockjax.clear();592 };593 $.mockjax.handler = function(i) {594 if ( arguments.length == 1 ) {595 return mockHandlers[i];596 }597 };598 $.mockjax.mockedAjaxCalls = function() {599 return mockedAjaxCalls;600 };601 $.mockjax.unfiredHandlers = function() {602 var results = [];603 for (var i=0, len=mockHandlers.length; i<len; i++) {604 var handler = mockHandlers[i];605 if (handler !== null && !handler.fired) {606 results.push(handler);607 }608 }609 return results;610 };611 $.mockjax.unmockedAjaxCalls = function() {612 return unmockedAjaxCalls;613 };...

Full Screen

Full Screen

core.js

Source:core.js Github

copy

Full Screen

1var testData = {2 one: "first",3 two: "second",4 v: "test",5 arr: ["AA","BB","CC"],6 dict: {"leovinus":"this","scraliontis":"that","brobostigon":"other"},7 fun: function () {8 return 'RETURNED';9 },10 html: '<a>'11};12var R = function ( tmpl, data ) {13 try {14 return jQuery.tmpl( tmpl, data ).text();15 }16 catch ( e ) {17 if ( typeof e === 'string' ) {18 return 'ERROR: ' + e;19 }20 return e;21 }22};23function test_handler( test_name, res, exp ) {24 var is_err = ($.isFunction(exp) && exp.prototype instanceof Error);25 if ( is_err && res instanceof exp ) {26 ok( res instanceof exp, test_name );27 }28 else {29 same( res, exp, test_name );30 }31}32// these are used throughout to test if tag blocks suppress them33jQuery.tmpl.tag.syntax_error = { open: "throw SyntaxError('test syntax error');" };34jQuery.tmpl.tag.reference_error = { open: "throw ReferenceError('test reference error');" };35jQuery.tmpl.tag.type_error = { open: "throw TypeError('test type error');" };36module("Basics");37 test("Basic Function", function() {38 test_handler( 'plain text passes through untouched', R('lorem ipsum', testData), 'lorem ipsum' );39 // TODO fixme40 //test_handler( 'whitespace is left untouched', R('\n\tlorem\n\n\tipsum \t', testData), '\n\tlorem\n\n\tipsum \t' );41 test_handler( 'simple variable output', R("${ one }", testData), "first" );42 // throw errors with incomplete syntax43 test_handler( 'multi word variable tag', R("${ a b c }}"), SyntaxError );44 test_handler( "_ (underscore) cannot by used by data", R('${ _ }', {'_':'foo'}), TypeError );45 test_handler( "$ cannot be used by data", R('${ $ }', {'$':'foo'}), TypeError );46 });47 // test errors are passed back correctly48 test("Error Passing", function(){49 test_handler( 'syntax', R("{{syntax_error }}", testData), SyntaxError );50 test_handler( 'reference', R("{{reference_error }}", testData), ReferenceError );51 test_handler( 'type', R("{{type_error }}", testData), TypeError );52 });53 // newlines should work because: ${ foo + "\n" } and they have whitespace management benefits54 test("Newlines / Escaping", function(){55 test_handler( "newlines do not kill tags", R('${\n \none\n }', testData), 'first');56 // TODO fixme57 //test_handler( "newlines in strings don't kill tags", R('${ "on\ne" }', testData), 'on\ne' );58 //test_handler( "returns do not kill tags", R('${\r \r\none\r\n }', testData), 'first');59 //test_handler( "returns in strings don't kill tags", R('${ "on\re" }', testData), 'on\re' );60 //test_handler( "slashes in strings don't kill tags", R('${ "on\\e" }', testData), 'on\\e');61 //test_handler( "newlines don't kill parsing", R('a\nb\nc${ 8 }.'), 'a\nb\nc8.');62 });63 test("Empty Tag", function() {64 // TODO fixme65 //test_handler( 'default', R("{{}}", testData), '{{}}' );66 //test_handler( 'with whitespace', R("{{ }}"), '{{ }}' );67 //test_handler( 'with tabs whitespace', R("{{\t\t}}"), '{{\t\t}}' );68 });69 test("Incorrect Nesting", function() {70 test_handler( 'default', R("{{if 1}}{{if 1}}{{/if}}", testData), SyntaxError );71 test_handler( 'extra /if', R("{{if 1}}{{/if}}{{/if}}", testData), SyntaxError );72 test_handler( 'but terminated', R("{{if 1}}{{each arr}}{{/if}}{{/each}}", testData), SyntaxError );73 });74 test("Ignore Malformed Tags", function() {75 test_handler( 'a {{one } b', R("a {{one } b", testData), 'a {{one } b' );76 test_handler( 'first} {{second }', R("${ one }} {{two }", testData), 'first} {{two }' );77 test_handler( '{{one }', R('{{one }', testData), '{{one }' );78 });79 // reserved words80 test("Reserved Words", function(){81 // TODO fixme82 //test_handler( "Disallow new operator", R('${ new Object() }',{}), SyntaxError );83 //test_handler( "Disallow delete operator", R('${ delete a }',{a:1}), SyntaxError );84 test_handler( "Disallow function operator", R('${ function(){} }',{}), SyntaxError );85 test_handler( "Disallow return", R('${ return a }',{a:1}), SyntaxError );86 test_handler( "Disallow for", R('${ for a }',{a:1}), SyntaxError );87 test_handler( "Disallow do/while", R('${ do{ a }while(a) }',{a:1}), SyntaxError );88 test_handler( "Disallow if", R('${ if a }',{a:1}), SyntaxError );89 test_handler( "Disallow try/catch", R('${ try{b.s}catch(e){} }',{a:1}), SyntaxError );90 test_handler( "Disallow return keyword", R('${ return a }',{a:1}), SyntaxError );91 test_handler( "Disallow with keyword", R('${ with (s) }',{a:1}), SyntaxError );92 test_handler( "Disallow throw keyword", R('${ throw "foo" }',{a:1}), SyntaxError );93 });94 // these tests are a bit awkward because caching is done in $.render, not $.tmpl95 test("Caching via $.template() and .template()", function() {96 $.template('nametmpl', '<span>name: ${ v }</span>' );97 test_handler( "using a named template", $.tmpl('nametmpl', testData).text(), 'name: test' );98 var $elm = $( "<span>name: ${ v }</span>" );99 $elm.template('nametmpl2');100 test_handler( "using a named template created from a node", $.tmpl('nametmpl2', testData).text(), 'name: test' );101 });102 test("Bracketed Accessors", function(){103 test_handler( "foo[\"bar\"]", R('${ foo["bar"] }',{foo:{bar:'baz'}}), 'baz' );104 test_handler( "foo['bar']", R("${ foo['bar'] }",{foo:{bar:'baz'}}), 'baz' );105 });106 test("Escaping", function(){107 // TODO fixme108 //test_handler( 'echoing escapes html', R("${ 'foo<div>bar</div>baz' }"), 'foo&lt;div&gt;bar&lt;/div&gt;baz' );109 //test_handler( 'echoing escapes html (lookup)', R("${ r }", {r:'foo<div>bar</div>baz'}), 'foo&lt;div&gt;bar&lt;/div&gt;baz' );110 //test_handler( 'echoing escapes ampersands 1', R("${ '&' }"), '&amp;' );111 //test_handler( 'echoing escapes ampersands 2', R("${ '&amp;' }"), '&amp;amp;' );112 //test_handler( 'echoing escapes & < >', R("${ '-<&>-<&>-' }"), '-&lt;&amp;&gt;-&lt;&amp;&gt;-' );113 });114 test("Comments", function() {115 test_handler( "comments are removed", R('A{{! comments test }}B', testData), "AB" );116 test_handler( "comments are removed (2)", R('{{! inky }}foo{{! blinky }}', testData), 'foo' );117 // TODO fixme118 return;119 test_handler( "comments may include string of comments", R('A{{! comments "}}" test }}B', testData), "AB" );120 test_handler( "comments cannot nest other comments", R('A{# C{# E #}D #}B', testData), "AD #}B" );121 test_handler( "comments may include strings with escapes (double)", R('A{# comments "str\"ing" test #}B', testData), "AB" );122 test_handler( "comments may include strings with escapes (single)", R("A{# comments 'str\'ing' test #}B", testData), "AB" );123 test_handler( "comments may include tags", R("A{# {{= v }} #}B", testData), "AB" );124 test_handler( "comments may span lines", R("A{# \ncomments test\n #}B", testData), "AB" );125 test_handler( "comments may contain invalid content (invalid tag)", R('1{{! {{ INVALID_TAG }} }}2', testData), '12' );126 test_handler( "comments may contain invalid content (stray end tag)", R('1{{! {{/if}} }}2', testData), '12' );127 test_handler( "comments may contain invalid content (stray else)", R('1{{! {{else}} }}2', testData), '12' );128 test_handler( "comments may contain invalid content (invalid javascript)", R('1{{! {{if ...}} }}2', testData), '12' );129 });130 test("Variables", function() {131 test_handler( "variable replacement", R('${ one }', testData), "first" );132 test_handler( "many variables work", R('${ one }/${ two }', testData), "first/second" );133 test_handler( "alternative variable syntax", R('${ one }', testData), "first" );134 test_handler( "many variables work with alt syntax", R('${ one }/${ two }', testData), "first/second" );135 test_handler( "basic string output (double)", R('${ "string" }', testData), "string" );136 test_handler( "basic string output (single)", R("${ 'string' }", testData), "string" );137 test_handler( "string quote escapes (double)", R('${ "str\\"i\\"ng" }', testData), 'str"i"ng' );138 test_handler( "string quote escapes (single)", R("${ 'str\\'i\\'ng' }", testData), "str'i'ng" );139 // TODO fixme140 //test_handler( "string output with tag", R('${ "\\{\\{ tag \\}\\}" }', testData), "{{ tag }}" );141 //test_handler( "string output with end of tag", R('${ "\\}\\}" }', testData), "}}" );142 test_handler( 'empty variable tag (with tabs whitespace)', R("{{=\t\t}}", "self"), 'self' );143 test_handler( 'empty variable tag', R("{{= }}", "self"), 'self' );144 test_handler( 'empty variable tag (with space)', R("{{=}}", "self"), 'self' );145 test_handler( "variable lookup error suppression", R('${ is_undefined }', testData), '' );146 // TODO fixme147 //test_handler( "variable lookup error suppression (with member)", R('${ is_undefined.member }', testData), '' );148 test_handler( "variable and text (1)", R('A${ one }', testData), 'Afirst' );149 test_handler( "variable and text (2)", R('${ one }B', testData), 'firstB' );150 test_handler( "variable and text (3)", R('A${ one }B', testData), 'AfirstB' );151 test_handler( "lookups work for submembers", R('${ a.b.c }', {a:{b:{c:"abc"}}}), 'abc' );152 test_handler( "error suppression works for submembers", R('${ a.b.c }', {a:{b:{c:"abc"}}}), 'abc' );153 test_handler( "functions can be called with in tags", R('${ foo() }', { foo:function(s){ return "bar"; }}), 'bar' );154 test_handler( "functions pass strings correctly", R('${ foo("bar") }', { foo:function(s){ return s; }}), 'bar' );155 test_handler( "functions pass arguments correctly", R('${ foo(bar) }', { foo:function(s){ return s; }, 'bar':'baz'}), 'baz' );156 var cls = {157 toString:function () {return 'S';},158 toValue:function () {return 'V';}159 }160 test_handler( 'variables use toString, not toValue', R("${ foo }",{foo:cls}), 'S' );161 test_handler( 'comma passes variables correctly', R("${ dot,dot,comma,dash }",{dot:'.','comma':',','dash':'-'}), '-' );162 // TODO fixme163 // @borgar says: I don't like this: it should use foo() to be consistant with foo().bar()164 test_handler( 'variable gets called if it is callable', R("${ fun }", testData), 'RETURNED' );165 test_handler( 'last variable in sequence gets called if it is callable', R("${ obj.fun }",{obj: testData}), 'RETURNED' );166 var cls = {167 foo: function () {168 return { bar: function () {return 'BAZ'; } };169 }170 }171 test_handler( 'member functions in a sequence don\'t get called', R("${ foo.bar }", cls), '' );172 });173 test("Falsy Values", function(){174 test_handler( "(0)", R('${ 0 }'), '0' );175 test_handler( "(false)", R('${ false }'), 'false' );176 test_handler( "(null)", R('${ zero }'), '' ); // it's debatable what we want here177 test_handler( "(undefined)", R('${ undefined }'), '' );178 test_handler( "(\"\")", R('${ "" }'), '' );179 test_handler( "('')", R("${ '' }"), '' );180 });181 test("Falsy Lookups", function(){182 test_handler( "(false)", R('${ zero }', {zero: 0}), '0' );183 test_handler( "(false)", R('${ zero }', {zero: false}), 'false' );184 test_handler( "(null)", R('${ zero }', {zero: null}), '' ); // it's debatable what we want here185 test_handler( "(undefined)", R('${ zero }', {zero: undefined}), '' );186 test_handler( "('')", R('${ zero }', {zero: ""}), '' );187 });188 test("Javascript Operations", function(){189 test_handler( "string concatination", R('${ one + "foo" }', testData), "firstfoo" );190 test_handler( "adding", R('${ 1 + 5 }', testData), "6" );191 test_handler( "subtracting", R('${ 9 - 5 }', testData), "4" );192 test_handler( "modulo", R('${ 5 % 2 }', testData), "1" );193 test_handler( "unary minus", R('${ -n }',{n:10}), "-10" );194 test_handler( "unary plus", R('${ +n }',{n:"10"}), "10" );195 test_handler( "in operator", R('${ "bar" in foo }',{foo:{bar:'baz'}}), "true" );196 test_handler( "instanceof operator", R('${ foo instanceof Date }',{foo:new Date()}), "true" );197 test_handler( "typeof operator", R('${ typeof "str" }',{}), "string" );198 test_handler( "bitwise AND", R('${ n & 1 }',{n:5}), "1" );199 test_handler( "bitwise OR", R('${ n | 1 }',{n:4}), "5" );200 test_handler( "bitwise XOR", R('${ n ^ 1 }',{n:5}), "4" );201 test_handler( "bitwise NOT", R('${ ~n }',{n:5}), "-6" );202 test_handler( "left shift", R('${ n << 1 }',{n:5}), "10" );203 test_handler( "right shift", R('${ n >> 1 }',{n:5}), "2" );204 test_handler( "zero-fill right shift", R('${ n >>> 1 }',{n:5}), "2" );205 test_handler( "comparing ==", R('${ 1 == 5 }', testData), "false" );206 test_handler( "comparing !=", R('${ 1 != 5 }', testData), "true" );207 test_handler( "comparing ===", R('${ 5 === 5 }', testData), "true" );208 test_handler( "comparing !==", R('${ 5 !== 5 }', testData), "false" );209 test_handler( "comparing >=", R('${ 1 >= 5 }', testData), "false" );210 test_handler( "comparing >", R('${ 1 > 5 }', testData), "false" );211 test_handler( "comparing <=", R('${ 1 <= 5 }', testData), "true" );212 test_handler( "comparing <", R('${ 1 < 5 }', testData), "true" );213 test_handler( "Logical OR", R('${ zero || "FALSY" }',{ zero: 0 }), "FALSY" );214 test_handler( "Logical AND", R('${ zero && "TRUEY" }',{ zero: 1 }), "TRUEY" );215 test_handler( "Conditional Operator", R('${ zero ? "zero" : "other" }',{ zero: 1 }), "zero" );216 test_handler( "Unary logical NOT", R('${ !zero }',{ zero: 1 }), "false" );217 test_handler( "Single-Quoted Strings", R("${ 'test' }",{}), "test" );218 test_handler( "Single-Quoted Comparison", R("${ 'test' == testvar }",{ testvar: 'test' }), "true" );219 });220 test("Disallowed / Illegal", function(){221 // TODO fixme222 /*223 test_handler( "Disallow incremental assignment", R('${ a += 1 }', {a:1}), SyntaxError );224 test_handler( "Disallow decremental assignment", R('${ a -= 1 }', {a:1}), SyntaxError );225 test_handler( "Disallow multiply assignment", R('${ a *= 1 }', {a:1}), SyntaxError );226 test_handler( "Disallow division assignment", R('${ a /= 1 }', {a:1}), SyntaxError );227 test_handler( "Disallow left shift assignment", R('${ a <<= 1 }', {a:1}), SyntaxError );228 test_handler( "Disallow right shift assignment", R('${ a >>= 1 }', {a:1}), SyntaxError );229 test_handler( "Disallow zero-fill right shift assignment", R('${ a >>>= 1 }', {a:1}), SyntaxError );230 test_handler( "Disallow bitwise AND assignment", R('${ a &= 1 }', {a:1}), SyntaxError );231 test_handler( "Disallow bitwise OR assignment", R('${ a |= 1 }', {a:1}), SyntaxError );232 test_handler( "Disallow bitwise XOR assignment", R('${ a ^= 1 }', {a:1}), SyntaxError );233 test_handler( "Disallow literal object creation", R('${ { a:"a"} }', {a:1}), SyntaxError );234 test_handler( "Disallow literal array creation", R('${ [1,2,3] }', {a:1}), SyntaxError );235 test_handler( "Disallow decrement", R('${ --a }',{a:1}), SyntaxError );236 test_handler( "Disallow assignments", R('${ (a = 2) }',{a:1}), SyntaxError );237 */238 });239module("Commands");240 test("Create New Command", function(){241 $.getText = function ( str ) { return str.toUpperCase(); };242 $.tmpl.tag.trans = { open: "_.push($.getText($1));" };243 test_handler( "creating new command works", R('{{trans "translate" }}'), 'TRANSLATE' );244 $.tmpl.tag._ = $.tmpl.tag.trans;245 test_handler( "_ can by assigned a command", R('{{_ "translate" }}', {}), 'TRANSLATE' );246 delete $.getText;247 delete $.tmpl.tag.trans;248 delete $.tmpl.tag._;249 });250 test("Each {{ each }}", function() {251 test_handler( "loop", R('{{each arr}}${ $index }:${ this }/{{/each}}', testData), '0:AA/1:BB/2:CC/' );252 test_handler( "loop", R('{{each arr}}${ $index }:${ $value }/{{/each}}', testData), '0:AA/1:BB/2:CC/' );253 test_handler( "loop", R('{{each(i, item) arr}}${ i }:${ item }/{{/each }}', testData), '0:AA/1:BB/2:CC/' );254 test_handler( "loop", R('{{each arr}}${ $index }:${ this }/{{/each }}', testData), '0:AA/1:BB/2:CC/' );255 // TODO fixme256 //test_handler( "first", R('{{each dict}}${ $index }:{{if $first }}first{{else}}!first{{/if }}/{{/each }}', testData), 'leovinus:first/scraliontis:!first/brobostigon:!first/' );257 //test_handler( "first", R('{{each dict}}{{if !$first }}, {{/if }}${ $index }:${ this }}{{/each }}', testData), 'leovinus:this, scraliontis:that, brobostigon:other' );258 // TODO fixme259 //test_handler("html content", R('{{each arr}}<a>${ $index }</a>{{/each}}', testData), '<a>0</a><a>1</a><a>2</a>' );260 //test_handler("html content", R('{{each arr}}<a>${ this }</a>{{/each}}', testData), '<a>AA</a><a>BB</a><a>CC</a>' );261 //test_handler("html content", R('{{each this}}<a>${ data }</a>{{/each}}', [{data: 0}, {data: 1}, {data: 2}]), '<a>0</a><a>1</a><a>2</a>' );262 //test_handler("html content with newlines", R('{{each this}}\n<a>${ data }</a>\n{{/each}}', [{data: 0}, {data: 1}, {data: 2}]), '\n<a>0</a>\n\n<a>1</a>\n\n<a>2</a>\n' );263 test_handler( 'errors are passed back correctly (syntax)', R("{{each arr}}${ $i }{{syntax_error}}{{/each}}", testData), SyntaxError );264 test_handler( 'errors are passed back correctly (reference)', R("{{each arr}}${ $i }{{reference_error}}{{/each}}", testData), ReferenceError );265 test_handler( 'errors are passed back correctly (type)', R("{{each arr}}${ $i }{{type_error}}{{/each}}", testData), TypeError );266 });267 test("{{if}} and {{else}}", function() {268 test_handler( "if:true", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:true }), 'TRUE' );269 test_handler( "if:false", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:false }), 'FALSE' );270 test_handler( "if:null", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:null }), 'FALSE' );271 test_handler( "if:undefined", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:undefined }), 'FALSE' );272 test_handler( "if:[]", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:{} }), 'TRUE' );273 test_handler( "if:{}", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:[] }), 'TRUE' );274 test_handler( "if:''", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:"" }), 'FALSE' );275 test_handler( "if:A", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:"A" }), 'TRUE' );276 test_handler( "if:0", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:0 }), 'FALSE' );277 test_handler( "if:1", R('{{if a}}TRUE{{else}}FALSE{{/if}}', { a:1 }), 'TRUE' );278 test_handler( "/if ignores following text", R('{{if a}}TRUE{{else}}FALSE{{/if a}}', { a:1 }), 'TRUE' );279 test_handler( 'errors are passed back correctly (syntax)', R("{{if true}}{{syntax_error}}{{/if}}", testData), SyntaxError );280 test_handler( 'errors are passed back correctly (reference)', R("{{if true}}{{reference_error}}{{/if}}", testData), ReferenceError );281 test_handler( 'errors are passed back correctly (type)', R("{{if true}}{{type_error}}{{/if}}", testData), TypeError );282 });283 test("{{tmpl() template}}", function() {284 jQuery.template('test', '${ "test text" }');285 test_handler( "simple include", R('{{tmpl "test"}}'), 'test text' );286 jQuery.template('test2', '{{each arr}}[${ $value }]-{{/each }}');287 test_handler( "data access", R('{{tmpl "test2"}}', testData), '[AA]-[BB]-[CC]-' );288 var nestedData = {foo: 'bar'};289 jQuery.template('nested', '{{tmpl "nested0"}}');290 jQuery.template('nested0', '${ foo }');291 test_handler( "nested - 1 level", R('{{tmpl "nested"}}', nestedData), 'bar' );292 jQuery.template('nested0', '{{tmpl "nested1"}}');293 jQuery.template('nested1', '{{tmpl "nested2"}}');294 jQuery.template('nested2', '${ foo }');295 test_handler( "nested - 2 levels", R('{{tmpl "nested" }}', nestedData), 'bar' );296 nestedData = {foo: {bar: {sweet: 1} } };297 jQuery.template('nested2', '${ foo.bar.sweet }');298 test_handler( "nested - 2 levels - complex data", R('{{tmpl "nested" }}', nestedData), '1' );299 // TODO fixme300 jQuery.template('test', '${ $index }');301 //test_handler( "{{each}} index variable", R('{{each arr}}{{tmpl "test" }}{{/each}}', testData), '012' );302 jQuery.template('test', '${ n }');303 //test_handler( "{{each}} index variable", R('{{each(n, item) arr}}{{tmpl "test"}}{{/each}}', testData), '012' );304 jQuery.template('test', '${ item }');305 //test_handler( "{{each}} item variable", R('{{each(n, item) arr}}{{tmpl "test" }}{{/each}}', testData), 'AABBCC' );306 });307 test("Html Output Unecoded {{html }}", function(){308 // TODO fixme309 //test_handler("encoded", R('{{= html}}', testData), '&lt;a&gt;');310 //test_handler("unencoded", R('{{html html}}', testData), '<a>');311 });312module("Script Tag Caching");313 test("Template Reuse", function(){314 var template = $('#reuse'),315 data = {data: 'pass1'};316 var pass1 = template.tmpl(data).html();317 data = {data: 'pass2'};318 var pass2 = template.tmpl(data).html();319 ok( "simple reuse test", pass1 == 'pass1' && pass2 == 'pass2' );...

Full Screen

Full Screen

quantiModo.js

Source:quantiModo.js Github

copy

Full Screen

...34 $http(request).success(successHandler).error(function(data,status,headers,config){35 var error = "Error";36 if (data && data.error && data.error.message) error = data.error.message; 37 Bugsnag.notify("API Request to "+request.url+" Failed",error,{},"error");38 errorHandler(data,status,headers,config);39 });40 }, onRequestFailed);41 };42 // POST method with the added token43 QuantiModo.post = function(baseURL, requiredFields, items, successHandler, errorHandler){44 authService.getAccessToken().then(function(token){45 46 console.log("TOKKEN : ", token.accessToken);47 // configure params48 for (var i = 0; i < items.length; i++) 49 {50 var item = items[i];51 for (var j = 0; j < requiredFields.length; j++) { 52 if (!(requiredFields[j] in item)) { 53 throw 'missing required field in POST data; required fields: ' + requiredFields.toString(); 54 } 55 }56 }57 // configure request58 var request = { 59 method : 'POST', 60 url: config.getURL(baseURL),61 responseType: 'json', 62 headers : {63 "Authorization" : "Bearer " + token.accessToken,64 'Content-Type': "application/json"65 },66 data : JSON.stringify(items)67 };68 $http(request).success(successHandler).error(function(data,status,headers,config){69 var error = "Error";70 if (data && data.error && data.error.message) error = data.error.message; 71 Bugsnag.notify("API Request to "+request.url+" Failed",error,{},"error");72 errorHandler(data,status,headers,config);73 });74 }, errorHandler);75 };76 // get Measuremnets for user77 var getMeasurements = function(params, successHandler, errorHandler){78 QuantiModo.get('api/measurements',79 ['variableName', 'startTime', 'endTime', 'groupingWidth', 'groupingTimezone', 'source', 'unit','limit','offset','lastUpdated'],80 params,81 successHandler,82 errorHandler);83 };84 QuantiModo.getMeasurements = function(params){85 var defer = $q.defer();86 var response_array = [];...

Full Screen

Full Screen

event-handler.js

Source:event-handler.js Github

copy

Full Screen

...81 element.uidEvent = uid;82 eventRegistry[uid] = eventRegistry[uid] || {};83 return eventRegistry[uid];84}85function bootstrapHandler(element, fn) {86 return function handler(event) {87 event.delegateTarget = element;88 if (handler.oneOff) {89 EventHandler.off(element, event.type, fn);90 }91 return fn.apply(element, [event]);92 };93}94function bootstrapDelegationHandler(element, selector, fn) {95 return function handler(event) {96 const domElements = element.querySelectorAll(selector);97 for (let { target } = event; target && target !== this; target = target.parentNode) {98 for (let i = domElements.length; i--; '') {99 if (domElements[i] === target) {100 event.delegateTarget = target;101 if (handler.oneOff) {102 EventHandler.off(element, event.type, fn);103 }104 return fn.apply(target, [event]);105 }106 }107 }108 // To please ESLint109 return null;110 };111}112function findHandler(events, handler, delegationSelector = null) {113 const uidEventList = Object.keys(events);114 for (let i = 0, len = uidEventList.length; i < len; i++) {115 const event = events[uidEventList[i]];116 if (event.originalHandler === handler && event.delegationSelector === delegationSelector) {117 return event;118 }119 }120 return null;121}122function normalizeParams(originalTypeEvent, handler, delegationFn) {123 const delegation = typeof handler === 'string';124 const originalHandler = delegation ? delegationFn : handler;125 // allow to get the native events from namespaced events ('click.bs.button' --> 'click')126 let typeEvent = originalTypeEvent.replace(stripNameRegex, '');127 const custom = customEvents[typeEvent];128 if (custom) {129 typeEvent = custom;130 }131 const isNative = nativeEvents.indexOf(typeEvent) > -1;132 if (!isNative) {133 typeEvent = originalTypeEvent;134 }135 return [delegation, originalHandler, typeEvent];136}137function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) {138 if (typeof originalTypeEvent !== 'string' || !element) {139 return;140 }141 if (!handler) {142 handler = delegationFn;143 delegationFn = null;144 }145 const [delegation, originalHandler, typeEvent] = normalizeParams(146 originalTypeEvent,147 handler,148 delegationFn149 );150 const events = getEvent(element);151 const handlers = events[typeEvent] || (events[typeEvent] = {});152 const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null);153 if (previousFn) {154 previousFn.oneOff = previousFn.oneOff && oneOff;155 return;156 }157 const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, ''));158 const fn = delegation159 ? bootstrapDelegationHandler(element, handler, delegationFn)160 : bootstrapHandler(element, handler);161 fn.delegationSelector = delegation ? handler : null;162 fn.originalHandler = originalHandler;163 fn.oneOff = oneOff;164 fn.uidEvent = uid;165 handlers[uid] = fn;166 element.addEventListener(typeEvent, fn, delegation);167}168function removeHandler(element, events, typeEvent, handler, delegationSelector) {169 const fn = findHandler(events[typeEvent], handler, delegationSelector);170 if (!fn) {171 return;172 }173 element.removeEventListener(typeEvent, fn, Boolean(delegationSelector));174 delete events[typeEvent][fn.uidEvent];175}176function removeNamespacedHandlers(element, events, typeEvent, namespace) {177 const storeElementEvent = events[typeEvent] || {};178 Object.keys(storeElementEvent).forEach((handlerKey) => {179 if (handlerKey.indexOf(namespace) > -1) {180 const event = storeElementEvent[handlerKey];181 removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);182 }183 });184}185const EventHandler = {186 on(element, event, handler, delegationFn) {187 addHandler(element, event, handler, delegationFn, false);188 },189 one(element, event, handler, delegationFn) {190 addHandler(element, event, handler, delegationFn, true);191 },192 off(element, originalTypeEvent, handler, delegationFn) {193 if (typeof originalTypeEvent !== 'string' || !element) {194 return;195 }196 const [delegation, originalHandler, typeEvent] = normalizeParams(197 originalTypeEvent,198 handler,199 delegationFn200 );201 const inNamespace = typeEvent !== originalTypeEvent;202 const events = getEvent(element);203 const isNamespace = originalTypeEvent.charAt(0) === '.';204 if (typeof originalHandler !== 'undefined') {205 // Simplest case: handler is passed, remove that listener ONLY.206 if (!events || !events[typeEvent]) {207 return;208 }209 removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null);210 return;211 }212 if (isNamespace) {213 Object.keys(events).forEach((elementEvent) => {214 removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1));215 });216 }217 const storeElementEvent = events[typeEvent] || {};218 Object.keys(storeElementEvent).forEach((keyHandlers) => {219 const handlerKey = keyHandlers.replace(stripUidRegex, '');220 if (!inNamespace || originalTypeEvent.indexOf(handlerKey) > -1) {221 const event = storeElementEvent[keyHandlers];222 removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);223 }224 });225 },226 trigger(element, event, args) {227 if (typeof event !== 'string' || !element) {228 return null;229 }230 const typeEvent = event.replace(stripNameRegex, '');231 const inNamespace = event !== typeEvent;232 const isNative = nativeEvents.indexOf(typeEvent) > -1;233 let jQueryEvent;234 let bubbles = true;235 let nativeDispatch = true;236 let defaultPrevented = false;...

Full Screen

Full Screen

event-handler.spec.js

Source:event-handler.spec.js Github

copy

Full Screen

1import EventHandler from '../../../src/dom/event-handler'2/** Test helpers */3import { getFixture, clearFixture } from '../../helpers/fixture'4describe('EventHandler', () => {5 let fixtureEl6 beforeAll(() => {7 fixtureEl = getFixture()8 })9 afterEach(() => {10 clearFixture()11 })12 describe('on', () => {13 it('should not add event listener if the event is not a string', () => {14 fixtureEl.innerHTML = '<div></div>'15 const div = fixtureEl.querySelector('div')16 EventHandler.on(div, null, () => {})17 EventHandler.on(null, 'click', () => {})18 expect().nothing()19 })20 it('should add event listener', done => {21 fixtureEl.innerHTML = '<div></div>'22 const div = fixtureEl.querySelector('div')23 EventHandler.on(div, 'click', () => {24 expect().nothing()25 done()26 })27 div.click()28 })29 it('should add namespaced event listener', done => {30 fixtureEl.innerHTML = '<div></div>'31 const div = fixtureEl.querySelector('div')32 EventHandler.on(div, 'bs.namespace', () => {33 expect().nothing()34 done()35 })36 EventHandler.trigger(div, 'bs.namespace')37 })38 it('should add native namespaced event listener', done => {39 fixtureEl.innerHTML = '<div></div>'40 const div = fixtureEl.querySelector('div')41 EventHandler.on(div, 'click.namespace', () => {42 expect().nothing()43 done()44 })45 EventHandler.trigger(div, 'click')46 })47 it('should handle event delegation', done => {48 EventHandler.on(document, 'click', '.test', () => {49 expect().nothing()50 done()51 })52 fixtureEl.innerHTML = '<div class="test"></div>'53 const div = fixtureEl.querySelector('div')54 div.click()55 })56 })57 describe('one', () => {58 it('should call listener just one', done => {59 fixtureEl.innerHTML = '<div></div>'60 let called = 061 const div = fixtureEl.querySelector('div')62 const obj = {63 oneListener() {64 called++65 }66 }67 EventHandler.one(div, 'bootstrap', obj.oneListener)68 EventHandler.trigger(div, 'bootstrap')69 EventHandler.trigger(div, 'bootstrap')70 setTimeout(() => {71 expect(called).toEqual(1)72 done()73 }, 20)74 })75 })76 describe('off', () => {77 it('should not remove a listener', () => {78 fixtureEl.innerHTML = '<div></div>'79 const div = fixtureEl.querySelector('div')80 EventHandler.off(div, null, () => {})81 EventHandler.off(null, 'click', () => {})82 expect().nothing()83 })84 it('should remove a listener', done => {85 fixtureEl.innerHTML = '<div></div>'86 const div = fixtureEl.querySelector('div')87 let called = 088 const handler = () => {89 called++90 }91 EventHandler.on(div, 'foobar', handler)92 EventHandler.trigger(div, 'foobar')93 EventHandler.off(div, 'foobar', handler)94 EventHandler.trigger(div, 'foobar')95 setTimeout(() => {96 expect(called).toEqual(1)97 done()98 }, 20)99 })100 it('should remove all the events', done => {101 fixtureEl.innerHTML = '<div></div>'102 const div = fixtureEl.querySelector('div')103 let called = 0104 EventHandler.on(div, 'foobar', () => {105 called++106 })107 EventHandler.on(div, 'foobar', () => {108 called++109 })110 EventHandler.trigger(div, 'foobar')111 EventHandler.off(div, 'foobar')112 EventHandler.trigger(div, 'foobar')113 setTimeout(() => {114 expect(called).toEqual(2)115 done()116 }, 20)117 })118 it('should remove all the namespaced listeners if namespace is passed', done => {119 fixtureEl.innerHTML = '<div></div>'120 const div = fixtureEl.querySelector('div')121 let called = 0122 EventHandler.on(div, 'foobar.namespace', () => {123 called++124 })125 EventHandler.on(div, 'foofoo.namespace', () => {126 called++127 })128 EventHandler.trigger(div, 'foobar.namespace')129 EventHandler.trigger(div, 'foofoo.namespace')130 EventHandler.off(div, '.namespace')131 EventHandler.trigger(div, 'foobar.namespace')132 EventHandler.trigger(div, 'foofoo.namespace')133 setTimeout(() => {134 expect(called).toEqual(2)135 done()136 }, 20)137 })138 it('should remove the namespaced listeners', done => {139 fixtureEl.innerHTML = '<div></div>'140 const div = fixtureEl.querySelector('div')141 let calledCallback1 = 0142 let calledCallback2 = 0143 EventHandler.on(div, 'foobar.namespace', () => {144 calledCallback1++145 })146 EventHandler.on(div, 'foofoo.namespace', () => {147 calledCallback2++148 })149 EventHandler.trigger(div, 'foobar.namespace')150 EventHandler.off(div, 'foobar.namespace')151 EventHandler.trigger(div, 'foobar.namespace')152 EventHandler.trigger(div, 'foofoo.namespace')153 setTimeout(() => {154 expect(calledCallback1).toEqual(1)155 expect(calledCallback2).toEqual(1)156 done()157 }, 20)158 })159 it('should remove the all the namespaced listeners for native events', done => {160 fixtureEl.innerHTML = '<div></div>'161 const div = fixtureEl.querySelector('div')162 let called = 0163 EventHandler.on(div, 'click.namespace', () => {164 called++165 })166 EventHandler.on(div, 'click.namespace2', () => {167 called++168 })169 EventHandler.trigger(div, 'click')170 EventHandler.off(div, 'click')171 EventHandler.trigger(div, 'click')172 setTimeout(() => {173 expect(called).toEqual(2)174 done()175 }, 20)176 })177 it('should remove the specified namespaced listeners for native events', done => {178 fixtureEl.innerHTML = '<div></div>'179 const div = fixtureEl.querySelector('div')180 let called1 = 0181 let called2 = 0182 EventHandler.on(div, 'click.namespace', () => {183 called1++184 })185 EventHandler.on(div, 'click.namespace2', () => {186 called2++187 })188 EventHandler.trigger(div, 'click')189 EventHandler.off(div, 'click.namespace')190 EventHandler.trigger(div, 'click')191 setTimeout(() => {192 expect(called1).toEqual(1)193 expect(called2).toEqual(2)194 done()195 }, 20)196 })197 it('should remove a listener registered by .one', done => {198 fixtureEl.innerHTML = '<div></div>'199 const div = fixtureEl.querySelector('div')200 const handler = () => {201 throw new Error('called')202 }203 EventHandler.one(div, 'foobar', handler)204 EventHandler.off(div, 'foobar', handler)205 EventHandler.trigger(div, 'foobar')206 setTimeout(() => {207 expect().nothing()208 done()209 }, 20)210 })211 it('should remove the correct delegated event listener', () => {212 const element = document.createElement('div')213 const subelement = document.createElement('span')214 element.appendChild(subelement)215 const anchor = document.createElement('a')216 element.appendChild(anchor)217 let i = 0218 const handler = () => {219 i++220 }221 EventHandler.on(element, 'click', 'a', handler)222 EventHandler.on(element, 'click', 'span', handler)223 fixtureEl.appendChild(element)224 EventHandler.trigger(anchor, 'click')225 EventHandler.trigger(subelement, 'click')226 // first listeners called227 expect(i).toEqual(2)228 EventHandler.off(element, 'click', 'span', handler)229 EventHandler.trigger(subelement, 'click')230 // removed listener not called231 expect(i).toEqual(2)232 EventHandler.trigger(anchor, 'click')233 // not removed listener called234 expect(i).toEqual(3)235 EventHandler.on(element, 'click', 'span', handler)236 EventHandler.trigger(anchor, 'click')237 EventHandler.trigger(subelement, 'click')238 // listener re-registered239 expect(i).toEqual(5)240 EventHandler.off(element, 'click', 'span')241 EventHandler.trigger(subelement, 'click')242 // listener removed again243 expect(i).toEqual(5)244 })245 })...

Full Screen

Full Screen

ChangeHandlerMediator-dbg.js

Source:ChangeHandlerMediator-dbg.js Github

copy

Full Screen

1/*!2 * UI development toolkit for HTML5 (OpenUI5)3 * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.4 * Licensed under the Apache License, Version 2.0 - see LICENSE.txt.5 */6sap.ui.define([7 "jquery.sap.global"8], function(9 jQuery10) {11 "use strict";12 /**13 * Change Handler Mediator to manage the requirements for the change handlers14 *15 * @alias sap.ui.fl.changeHandler.ChangeHandlerMediator16 *17 * @private18 * @author SAP SE19 * @version 1.50.520 *21 * @experimental Since 1.49.0 This class is experimental and provides only limited functionality. Also the API might be22 * changed in future.23 *24 */25 var ChangeHandlerMediator = { };26 /**27 * Array of relevant change handlers settings28 * Initialize with the required entries for AddODataField29 */30 ChangeHandlerMediator._aChangeHandlerSettings = [];31 ["addODataField", "addODataFieldWithLabel"].forEach(function (sScenario) {32 ["2.0", "1.0"].forEach(function (sVersion) {33 ChangeHandlerMediator._aChangeHandlerSettings.push({34 key: {35 "scenario": sScenario,36 "oDataServiceVersion": sVersion37 },38 content: {39 "requiredLibraries": {40 "sap.ui.comp": {41 "minVersion": "1.48",42 "lazy": false43 }44 }45 },46 scenarioInitialized: false47 });48 });49 });50 /**51 * Add change handler settings to the mediated list52 * @param {Object} mKey Collection of keys53 * @param {string} mKey.scenario The scenario name54 * @param {Object} mSettings The relevant settings for the change handler55 */56 ChangeHandlerMediator.addChangeHandlerSettings = function(mKey, mSettings) {57 var mNewChangeHandlerSettings;58 if (!(mKey && mSettings)){59 throw new Error('New entry in ChangeHandlerMediator requires a key and settings');60 }61 mNewChangeHandlerSettings = {62 key : mKey,63 content : mSettings,64 scenarioInitialized : false65 };66 var mExistingChangeHandlerSettings = this.getChangeHandlerSettings(mKey, true);67 var iIndex = this._aChangeHandlerSettings.indexOf(mExistingChangeHandlerSettings);68 // If entry already exists, extend existing content and set initialized to false69 if (iIndex > -1) {70 jQuery.extend(this._aChangeHandlerSettings[iIndex].content,71 mNewChangeHandlerSettings.content);72 this._aChangeHandlerSettings[iIndex].scenarioInitialized = false;73 } else {74 this._aChangeHandlerSettings.push(mNewChangeHandlerSettings);75 this._createChangeHandlerSettingsGetter(mNewChangeHandlerSettings);76 }77 };78 /**79 * Retrieves change handler settings from the mediated list80 * @param {Object} mKey Collection of keys81 * @param {boolean} bSkipInitialization If true, the scenario should not be initialized82 * @return {Object} The change handler settings83 */84 ChangeHandlerMediator.getChangeHandlerSettings = function(mKey, bSkipInitialization){85 var aKeys = Object.keys(mKey);86 var mFoundChangeHandlerSettings;87 if (aKeys.length > 0) {88 mFoundChangeHandlerSettings = this._aChangeHandlerSettings.filter(function(oEntry, iIndex){89 var aExistingKeys = Object.keys(oEntry.key);90 if (aExistingKeys.length === aKeys.length) {91 var aMatchingKeys = aKeys.filter(function(sKey){92 if (oEntry.key[sKey] === mKey[sKey]){93 return true;94 }95 });96 // Only return the object with the exact matching keys97 if (aMatchingKeys.length === aKeys.length){98 return true;99 }100 }101 })[0];102 // Try to initialize the corresponding scenario103 if (!bSkipInitialization && mFoundChangeHandlerSettings104 && !mFoundChangeHandlerSettings.scenarioInitialized) {105 mFoundChangeHandlerSettings.scenarioInitialized106 = this._initializeScenario(mFoundChangeHandlerSettings);107 }108 }109 if (bSkipInitialization ||110 (mFoundChangeHandlerSettings && mFoundChangeHandlerSettings.scenarioInitialized)){111 return mFoundChangeHandlerSettings;112 }113 };114 /**115 * Initializes a scenario that is required by the application116 * (e.g. for AddODataField -> load the required libraries)117 * @param {Object} mFoundChangeHandlerSettings The Change Handler Settings for the scenario118 * @return {boolean} true if properly initialized119 */120 ChangeHandlerMediator._initializeScenario = function(mFoundChangeHandlerSettings){121 var sLibraryName;122 if (mFoundChangeHandlerSettings.content.requiredLibraries){123 try {124 var aLibraries = Object.keys(mFoundChangeHandlerSettings.content.requiredLibraries);125 aLibraries.forEach(function(sLibrary){126 sLibraryName = sLibrary;127 sap.ui.getCore().loadLibrary(sLibrary);128 });129 var iIndex = this._aChangeHandlerSettings.indexOf(mFoundChangeHandlerSettings);130 // Update the entry on the array131 this._aChangeHandlerSettings[iIndex].scenarioInitialized = true;132 return true;133 } catch (e){134 jQuery.sap.log.warning("Required library not available: " + sLibraryName + " - "135 + mFoundChangeHandlerSettings.key.scenario + " could not be initialized");136 return false;137 }138 }139 };140 ChangeHandlerMediator._createChangeHandlerSettingsGetter = function(mChangeHandlerSettings){141 var sGetterName = 'get' + jQuery.sap.charToUpperCase(mChangeHandlerSettings.key.scenario) + 'Settings';142 if (!ChangeHandlerMediator[sGetterName]) {143 /**144 * Retrieves the settings for the specified scenario, getting the oData145 * service version from the control and ensures that a create function is146 * available for the change handler147 * @param {sap.ui.core.Control} oControl The control for the scenario148 * @return {Object} The Change Handler Settings for the scenario149 */150 ChangeHandlerMediator[sGetterName] = function(oControl){151 var sODataServiceVersion;152 var mFoundChangeHandlerSettings;153 try {154 sODataServiceVersion = oControl.getModel().getMetaModel().getProperty("/dataServices/dataServiceVersion");155 } catch (e) {156 jQuery.sap.log.warning("Data service version could not be retrieved");157 }158 mFoundChangeHandlerSettings = this.getChangeHandlerSettings({159 "scenario" : mChangeHandlerSettings.key.scenario,160 "oDataServiceVersion" : sODataServiceVersion161 });162 // Without a create function, the settings should not be returned163 if (mFoundChangeHandlerSettings &&164 mFoundChangeHandlerSettings.content &&165 mFoundChangeHandlerSettings.content.createFunction){166 return mFoundChangeHandlerSettings;167 }168 };169 }170 };171 // Create getters172 ChangeHandlerMediator._aChangeHandlerSettings.forEach(function (mChangeHandlerSettings) {173 ChangeHandlerMediator._createChangeHandlerSettingsGetter(mChangeHandlerSettings);174 });175 return ChangeHandlerMediator;...

Full Screen

Full Screen

DomEventMixin.js

Source:DomEventMixin.js Github

copy

Full Screen

...54 },55 56 AttachDomEvent : function(element, eventName, eventHandlerName, fireIfDisabled)57 {58 var eventHandler = this.CreateEventHandler(eventHandlerName, fireIfDisabled);59 // if such entry exist already - detach it first60 var oldRegister = this.GetHandlerRegister(element, eventName, eventHandlerName);61 if (oldRegister != null)62 {63 this.DetachDomEvent(oldRegister.Element, oldRegister.EventName, eventHandlerName);64 }65 66 // register the new entry67 var eventRegister = { 68 "Element" : element, 69 "EventName" : eventName, 70 "HandlerName" : eventHandlerName, 71 "Handler" : eventHandler 72 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = function (argosy) {2 argosy.pattern({3 }, function (msg, respond) {4 respond(null, {5 })6 })7}8### argosy.pattern(pattern, function (msg, respond) { ... })9The pattern method is used to define a handler for a message pattern. The pattern is a JSON object that is used to match incoming messages. The pattern is matched using [jsonist](

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var argosyPattern = require('argosy-pattern')3var argosyService = argosy()4var argosyPatternService = argosyPattern({5})6argosyService.pipe(argosyPatternService).pipe(argosyService)7argosyService.accept({8 add: function (a, b, callback) {9 callback(null, a + b)10 }11})12argosyPatternService.accept({13 add: function (a, b, callback) {14 callback(null, a + b)15 }16})17argosyService.on('error', console.error)18argosyPatternService.on('error', console.error)19argosyService.act('add:1,2', function (err, result) {20 console.log(err, result)21})22argosyPatternService.act('add:1,2', function (err, result) {23 console.log(err, result)24})

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var service = argosy()3service.pipe(argosy.accept({4 'test': function (input, cb) {5 cb(null, input)6 }7})).pipe(service)8service.on('service', function (service) {9 service.test('hello', function (err, result) {10 })11})12var argosy = require('argosy')13var service = argosy()14service.pipe(argosy.accept({15 'test': function (input, cb) {16 cb(null, input)17 }18})).pipe(service)19service.on('service', function (service) {20 service.test('hello', function (err, result) {21 })22})23var argosy = require('argosy')24var service = argosy()25service.pipe(argosy.accept({26 'test': function (input, cb) {27 cb(null, input)28 }29})).pipe(service)30service.on('service', function (service) {31 service.test('hello', function (err, result) {32 })33})34var argosy = require('argosy')35var service = argosy()36service.pipe(argosy.accept({37 'test': function (input, cb) {38 cb(null, input)39 }40})).pipe(service)41service.on('service', function (service) {42 service.test('hello', function (err, result) {43 })44})45var argosy = require('argosy')46var service = argosy()47service.pipe(argosy.accept({48 'test': function (input, cb) {49 cb(null, input)50 }51})).pipe(service)52service.on('service', function (service) {53 service.test('hello', function (err, result) {54 })55})

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var argosyPattern = require('argosy-pattern')3var service = argosy()4service.use(argosyPattern({5}, function (msg, respond) {6 respond(null, { greeting: 'Hello ' + msg.greet })7}))8service.listen(8000)9var argosy = require('argosy')10var argosyPattern = require('argosy-pattern')11var service = argosy()12service.use(argosyPattern({13}, function (msg, respond) {14 respond(null, { greeting: 'Hello ' + msg.greet })15}))16service.listen(8000)17var argosy = require('argosy')18var argosyPattern = require('argosy-pattern')19var service = argosy()20service.use(argosyPattern({21}, function (msg, respond) {22 respond(null, { greeting: 'Hello ' + msg.greet })23}))24service.listen(8000)25var argosy = require('argosy')26var argosyPattern = require('argosy-pattern')27var service = argosy()28service.use(argosyPattern({29}, function (msg, respond) {30 respond(null, { greeting: 'Hello ' + msg.greet })31}))32service.listen(8000)33var argosy = require('argosy')34var argosyPattern = require('argosy-pattern')35var service = argosy()36service.use(argosyPattern({37}, function (msg, respond) {38 respond(null, { greeting: 'Hello ' + msg.greet })39}))40service.listen(8000)41var argosy = require('argosy')

Full Screen

Using AI Code Generation

copy

Full Screen

1var argosy = require('argosy')2var seneca = require('seneca')()3var service = argosy()4service.use(argosy.pattern({5}), function (msg, respond) {6 respond(null, {7 })8})9seneca.use('seneca-amqp-transport')10seneca.listen({11})12seneca.ready(function () {13 service.listen(seneca.export('transport'))14})

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 argos 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