summaryrefslogtreecommitdiffstats
path: root/die.mjs
blob: 6b3d4fc60c4592d767e00d5f190ec305c200194c (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
class Die {
    constructor(elt) {
	this.elt = elt

        this.value = '--'
        this._boundRollHandler = this.rollHandler.bind(this)
        this.disable()
    }

    get valueElt() {
        if (this._valueElt === undefined) {
            this._valueElt = this.elt.querySelector('.value')
        }
        return this._valueElt
    }

    get value() {
        return this.valueElt.innerText
    }

    set value(val) {
        this.valueElt.innerText = val
    }

    get button() {
        if (this._button === undefined) {
            this._button = this.elt.querySelector('button')
        }
        return this._button
    }

    enable() {
        this.elt.classList.add('enabled')
	this.elt.classList.remove('disabled')
	this.button.disabled = false
	this.button.addEventListener('click', this._boundRollHandler)
    }

    disable() {
	this.elt.classList.add('disabled')
	this.elt.classList.remove('enabled')
	this.button.disabled = true
	this.button.removeEventListener('click', this._boundRollHandler)
    }

    get onChanged() {
	if (this._onChanged !== undefined) {
	    return this._onChanged
	}
	return () => {}
    }

    set onChanged(fn) {
	this._onChanged = fn
    }

    rollHandler() {
	this.value = Math.floor(Math.random() * Die.size) + 1
	this.onChanged(this.value)
    }
}
Die.size = 20

export default Die