summaryrefslogtreecommitdiff
path: root/assets/js/core/base.js
blob: 4ea3ffc259a9d2580a7f56041e5a7b8563a20592 (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
var KB = {
    components: {},
    utils: {},
    html: {},
    http: {},
    listeners: {
        clicks: {},
        internals: {}
    }
};

KB.on = function (eventType, callback) {
    if (! this.listeners.internals.hasOwnProperty(eventType)) {
        this.listeners.internals[eventType] = [];
    }

    this.listeners.internals[eventType].push(callback);
};

KB.trigger = function (eventType, eventData) {
    if (this.listeners.internals.hasOwnProperty(eventType)) {
        for (var i = 0; i < this.listeners.internals[eventType].length; i++) {
            if (! this.listeners.internals[eventType][i](eventData)) {
                break;
            }
        }
    }
};

KB.onClick = function (selector, callback) {
    this.listeners.clicks[selector] = callback;
};

KB.listen = function () {
    var self = this;

    function onClick(e) {
        for (var selector in self.listeners.clicks) {
            if (self.listeners.clicks.hasOwnProperty(selector) && e.target.matches(selector)) {
                e.preventDefault();
                self.listeners.clicks[selector](e);
            }
        }
    }

    document.addEventListener('click', onClick, false);
};

KB.component = function (name, object) {
    this.components[name] = object;
};

KB.getComponent = function (name, containerElement, options) {
    var object = this.components[name];
    return new object(containerElement, options);
};

KB.render = function () {
    for (var name in this.components) {
        var elementList = document.querySelectorAll('.js-' + name);

        for (var i = 0; i < elementList.length; i++) {
            if (this.components.hasOwnProperty(name)) {
                var options;

                if (elementList[i].dataset.params) {
                    options = JSON.parse(elementList[i].dataset.params);
                }

                var component = KB.getComponent(name, elementList[i], options);
                component.render();
                elementList[i].className = elementList[i].className + '-rendered';
            }
        }
    }
};