~sirn/fanboi2

ref: 5b482cfc1bfb0bb1e89715cb57c7bac864391768 fanboi2/assets/app/javascripts/components/topic/topic_new_post.ts -rw-r--r-- 1.5 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
import {ITopicEventHandler} from './base';
import {Post} from '../../models/post';
import {dispatchCustomEvent} from '../../utils/elements';
import {ResourceError} from '../../utils/errors';
import {LoadingState} from '../../utils/loading';


export class TopicNewPost implements ITopicEventHandler {
    loadingState: LoadingState;

    constructor(public topicId: number, public element: Element) {
        this.loadingState = new LoadingState();
    }

    bind(e: CustomEvent): void {
        let params: any = e.detail.params;
        let callback: ((lastPostNumber: number) => void) = e.detail.callback;
        let errCb: ((error: ResourceError) => void) = e.detail.errorCallback;

        if (!params) { throw new Error('newPost require a params'); }

        this.loadingState.bind(() => {
            return Post.createOne(this.topicId, params).then(() => {
                dispatchCustomEvent(this.element, 'postCreated');
                dispatchCustomEvent(this.element, 'loadPosts', {
                    callback: (lastPostNumber: number) => {
                        if (callback) {
                            callback(lastPostNumber);
                        }
                    }
                });
            }).catch((error: ResourceError) => {
                if (errCb) {
                    errCb(error);
                    dispatchCustomEvent(this.element, 'postCreateError', {
                        error: error
                    });
                }
            });
        });
    }
}