diff options
author | Noah Loomans <noahloomans@gmail.com> | 2017-01-08 11:48:13 +0100 |
---|---|---|
committer | Noah Loomans <noahloomans@gmail.com> | 2017-01-08 11:48:13 +0100 |
commit | 320c18af3ee9cbeaaae3d4796dd7f15a5ac90889 (patch) | |
tree | d63339d425a2a6a20c883d896b9ed492272d6085 /public/javascripts/favorite.js | |
parent | 4e8da42863406764a659a7337e774ad216d356c9 (diff) | |
parent | dea89e1ec600b302a8db33dd48080b901aee7c7e (diff) |
Merge branch 'master' of github.com:nloomans/rooster-mml
Diffstat (limited to 'public/javascripts/favorite.js')
-rw-r--r-- | public/javascripts/favorite.js | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/public/javascripts/favorite.js b/public/javascripts/favorite.js new file mode 100644 index 0000000..9edc248 --- /dev/null +++ b/public/javascripts/favorite.js @@ -0,0 +1,79 @@ +/* global USERS */ + +const EventEmitter = require('events') + +const self = new EventEmitter() + +self._nodes = { + toggle: document.querySelector('.fav') +} + +self.get = function () { + try { + const localStorageUser = JSON.parse(window.localStorage.getItem('fav')) + if (localStorageUser == null) return + + const correctedUser = USERS.filter(function (user) { + return user.type === localStorageUser.type && + user.value === localStorageUser.value + })[0] + return correctedUser + } catch (e) { + self.delete() + return + } +} + +self.set = function (user) { + window.localStorage.setItem('fav', JSON.stringify(user)) + self._nodes.innerHTML = '' +} + +self.delete = function () { + window.localStorage.removeItem('fav') +} + +self.updateDom = function (isFavorite) { + if (isFavorite) { + self._nodes.toggle.innerHTML = '' + } else { + self._nodes.toggle.innerHTML = '' + } +} + +self.update = function (selectedUser) { + const currentUser = self.get() + + if (currentUser == null) { + self.updateDom(false) + return + } + + const isEqual = currentUser.type === selectedUser.type && + currentUser.index === selectedUser.index + + self.updateDom(isEqual) +} + +self.toggle = function (selectedUser) { + const currentUser = self.get() + const isEqual = currentUser != null && + currentUser.type === selectedUser.type && + currentUser.index === selectedUser.index + + if (isEqual) { + self.delete() + self.updateDom(false) + } else { + self.set(selectedUser) + self.updateDom(true) + } +} + +self._handleClick = function () { + self.emit('click') +} + +self._nodes.toggle.addEventListener('click', self._handleClick) + +module.exports = self |