~sirn/fanboi2

ref: 5b482cfc1bfb0bb1e89715cb57c7bac864391768 fanboi2/assets/app/javascripts/components/topic/topic_state.ts -rw-r--r-- 1.6 KiB
5b482cfcKridsada Thanabulpong 0.30.0 3 years ago
                                                                                
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
import {ITopicEventHandler} from './base';


export class TopicState implements ITopicEventHandler {
    stateName: string;

    constructor(public topicId: number, public element: Element) {
        this.stateName = `topic/${topicId}`;
    }

    bind(event: CustomEvent): void {
        switch (event.type) {
        case 'readState':
            this.bindReadState(event);
            break;
        case 'updateState':
            this.bindUpdateState(event);
            break;
        }
    }

    private bindReadState(e: CustomEvent): void {
        let name: string = e.detail.name;
        let callback: ((name: string, value: any) => void) = e.detail.callback;

        if (!name) { throw new Error('readState require a name'); }
        if (!callback) { throw new Error('readState require a callback'); }

        let state = this.readState();
        callback(name, state[name]);
    }

    private bindUpdateState(e: CustomEvent): void {
        let name: string = e.detail.name;
        let value: any = e.detail.value;
        let callback: ((name: string, value: any) => void) = e.detail.callback;

        if (!name) { throw new Error('updateState require a name'); }

        let state = this.readState();
        state[name] = value;
        localStorage.setItem(this.stateName, JSON.stringify(state));

        if (callback) {
            callback(name, value);
        }
    }

    private readState(): any {
        let state = {};
        let stateString = localStorage.getItem(this.stateName);

        if (stateString) {
            state = JSON.parse(stateString);
        }

        return state;
    }
}