UNPKG

1.64 kBJavaScriptView Raw
1const inherits = require('inherits');
2const Emitter = require('events').EventEmitter;
3const format = require('param-case');
4const extend = require('just-extend');
5
6module.exports = Switch;
7
8inherits(Switch, Emitter);
9
10function Switch (opts) {
11 if (!(this instanceof Switch)) return new Switch(opts);
12
13 this.switch = opts.container.querySelector('.settings-panel-switch');
14
15 if (!this.switch) {
16 this.switch = document.createElement('fieldset');
17 this.switch.className = 'settings-panel-switch';
18 opts.container.appendChild(this.switch);
19
20 var html = '';
21
22 if (Array.isArray(opts.options)) {
23 for (i = 0; i < opts.options.length; i++) {
24 let option = opts.options[i]
25 html += createOption(option, option);
26 }
27 } else {
28 for (let key in opts.options) {
29 html += createOption(opts.options[key], key);
30 }
31 }
32
33 this.switch.innerHTML = html;
34
35 this.switch.onchange = (e) => {
36 this.emit('input', e.target.getAttribute('data-value'));
37 }
38
39 setTimeout(() => {
40 this.emit('init', opts.value)
41 })
42 }
43
44 this.switch.id = opts.id;
45
46 this.update(opts);
47
48 function createOption (label, value) {
49 let htmlFor = `settings-panel-${format(opts.panel.id)}-${format(opts.id)}-input-${format(value)}`;
50
51 let html = `<input type="radio" class="settings-panel-switch-input" ${value === opts.value ? 'checked' : ''} id="${htmlFor}" name="${format(opts.id)}" data-value="${value}" title="${value}"/><label for="${htmlFor}" class="settings-panel-switch-label" title="${value}">${label}</label>`;
52 return html;
53 }
54}
55
56Switch.prototype.update = function (opts) {
57 return this;
58}
\No newline at end of file