aboutsummaryrefslogtreecommitdiff
path: root/public/javascripts/favorite.js
blob: 92c87f7ae660ea4e084882cc1b915a32579d925a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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 = '&#xE83A'
  }
}

self.update = function (selectedUser) {
  const currentUser = self.get()

  if (currentUser == null || selectedUser == 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