digd.js/lib/public/js/app.js

88 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-01-10 21:54:08 +00:00
(function () {
'use strict';
2018-01-12 09:03:41 +00:00
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector;
}
2018-01-10 21:54:08 +00:00
function $qs(qs) {
return document.querySelector(qs);
}
2018-01-12 09:03:41 +00:00
function $on(selector, eventname, cb) {
if (!$on._events[eventname]) {
$on._events[eventname] = $on._dispatcher(eventname);
document.addEventListener(eventname, $on._events[eventname]);
2018-01-10 21:54:08 +00:00
}
2018-01-12 09:03:41 +00:00
if (!$on._handlers[eventname]) {
$on._handlers[eventname] = {};
2018-01-10 21:54:08 +00:00
}
2018-01-12 09:03:41 +00:00
if (!$on._handlers[eventname][selector]) {
$on._handlers[eventname][selector] = [];
}
$on._handlers[eventname][selector].push(cb);
}
$on._events = {};
$on._handlers = {};
$on._dispatcher = function (eventname) {
return function (ev) {
//console.log('event: ' + ev.type);
if (!$on._handlers[eventname]) {
console.warn('no handlers for event');
return;
}
var matches = Object.keys($on._handlers[eventname]).some(function (selector) {
if (ev.target.matches(selector)) {
$on._handlers[eventname][selector].forEach(function (cb) { cb(ev); });
return true;
}
});
if (!matches) {
console.warn("no handlers for selector");
}
};
};
$on('body', 'click', function () {
console.log('woo-hoo, that tickles my body!');
});
var auth = localStorage.getItem('auth');
$qs('input.js-jwt').value = auth || '';
$on('button.js-jwt', 'click', function (/*ev*/) {
auth = $qs('input.js-jwt').value;
return window.fetch(
'/api/verify-auth'
, { method: 'GET'
, headers: new window.Headers({ 'Authorization': 'Bearer ' + auth })
}
).then(function (resp) {
return resp.json().then(function (data) {
if (data.error) {
console.error(data.error);
window.alert('Bad HTTP Response: ' + data.error.message);
throw new Error('Bad HTTP Response: ' + data.error.message);
}
console.log(data);
localStorage.setItem('auth', auth);
});
});
});
$on('input.js-zone', 'keyup', function (ev) {
$qs('code.js-zone').innerHTML = ev.target.value || ':zone';
// $qs('a.js-zone').setAttribute('data-href', ...)
$qs('a.js-zone').href =
$qs('a.js-zone').dataset.href.replace(/:zone/, ev.target.value || ':zone');
});
$on('input.js-name', 'keyup', function (ev) {
$qs('code.js-name').innerHTML = ev.target.value || ':name';
$qs('a.js-name').href =
$qs('a.js-name').dataset.href.replace(/:name/, ev.target.value || ':name');
2018-01-10 21:54:08 +00:00
});
}());