Last active
September 16, 2016 01:35
-
-
Save baltazarparra/2c00a151c42cb3513775c750314deb83 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(jokenpo){ | |
'use strict'; | |
var $rock = document.querySelector('[data-js="rock"]'); | |
var $paper = document.querySelector('[data-js="paper"]'); | |
var $scissor = document.querySelector('[data-js="scissor"]'); | |
var $userChoice = document.querySelector('[data-js="user-choice"]'); | |
var $cpuChoice = document.querySelector('[data-js="cpu-choice"]'); | |
var $userScore = document.querySelector('[data-js="userScore"]'); | |
var $cpuScore = document.querySelector('[data-js="cpuScore"]'); | |
var app = (function appController() { | |
return { | |
init: function init() { | |
this.initEvents(); | |
}, | |
initEvents: function initEvents() { | |
$rock.addEventListener('click', this.optionChoice('rock')); | |
$paper.addEventListener('click', this.optionChoice('paper')); | |
$scissor.addEventListener('click', this.optionChoice('scissor')); | |
}, | |
cpuChoice: function cpuChoice() { | |
var cpuChoice = Math.random(); | |
if (cpuChoice < 0.3) { | |
var cpuChoiceOutput = 'rock'; | |
$cpuChoice.setAttribute("src", cpuChoiceOutput + ".svg"); | |
return cpuChoiceOutput; | |
} else if (cpuChoice < 0.6) { | |
var cpuChoiceOutput = 'paper'; | |
$cpuChoice.setAttribute("src", cpuChoiceOutput + ".svg"); | |
return cpuChoiceOutput; | |
} | |
var cpuChoiceOutput = 'scissor'; | |
$cpuChoice.setAttribute("src", cpuChoiceOutput + ".svg"); | |
return cpuChoiceOutput; | |
}, | |
optionChoice: function optionChoice(option) { | |
return function () { | |
var cpuOption = app.cpuChoice(); | |
$userChoice.setAttribute("src", option + ".svg"); | |
jokenpo.play(option, cpuOption); | |
} | |
} | |
}; | |
})(); | |
app.init(); | |
})(window.jokenpo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Vou tentar explicar a ideia base de como você pode manter os valores usando uma "closure":
Só isso! Fazendo isso, a cada vez que você executar essa função, os valores internos serão diferentes. Mas se você usar o objeto retornado, você estará trabalhando com os valores guardados pela "closure".
Como fica na prática, seguindo os passos acima?
É só isso! Como é o funcionamento da closure? Vamos criar uma aplicação usando essa função:
Veja que, a cada vez que eu chamo
app.sum()
, é incrementado1
emvalue
.app
é o objeto retornado pela funçãomain
.O real uso da closure se dá quando você precisa criar mais de uma aplicação ao mesmo tempo, fazendo uma "concorrência" entre as duas aplicações, mas usando a mesma função:
Olha só que legal! Uma não interfere na outra! Essa é a ideia de usar closures =)
Consegui entender?