mirror of
https://github.com/0x1d/esp8266-laser.git
synced 2025-12-14 18:15:22 +01:00
73 lines
2.8 KiB
JavaScript
73 lines
2.8 KiB
JavaScript
var Sui = {
|
|
ready: (callback) => {
|
|
document.addEventListener("DOMContentLoaded", function() {
|
|
callback();
|
|
}, false);
|
|
},
|
|
select: (selector) => {
|
|
return document.querySelectorAll(selector);
|
|
},
|
|
link: (node) => {
|
|
return (actuator) => {
|
|
let update = actuator.handler || function(actuator) {
|
|
Sui.http.ajax({
|
|
method: actuator.method,
|
|
endpoint: actuator.api,
|
|
data: actuator.data ?
|
|
actuator.data.call(this) : [this.value],
|
|
cache: false
|
|
}, actuator.onResponse || null);
|
|
};
|
|
Sui.select(actuator.selector).forEach( (domEl) =>{
|
|
let handle = function(event) {
|
|
update.call(this, actuator);
|
|
}
|
|
domEl.addEventListener(actuator.event, handle)
|
|
});
|
|
};
|
|
},
|
|
util: {
|
|
|
|
/**
|
|
* serialize a flat json object
|
|
*/
|
|
serialize: (obj) => {
|
|
var str = [];
|
|
for(var p in obj){
|
|
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
|
|
}
|
|
return str.join("&");
|
|
}
|
|
},
|
|
http: {
|
|
|
|
/**
|
|
* ajax request
|
|
* {
|
|
* method: <'GET', 'POST', whatever >,
|
|
* endpoint: <URL to the service endpoint>,
|
|
* async: <true or false>, (default true)
|
|
* data: <json object with data to transmit>,
|
|
* cache: <true or false> (default false)
|
|
* }
|
|
*/
|
|
ajax: (config, callback) => {
|
|
var cache = config.cache || false;
|
|
var data = config.data || {};
|
|
if(!cache) {
|
|
data['_'] = new Date().getTime();
|
|
}
|
|
var serializedData = data; //Sui.util.serialize(data);
|
|
var endPointUrl = (config.method === 'GET' || config.method === 'DELETE') && data ? config.endpoint+'?'+serializedData : config.endpoint;
|
|
var postData = config.method === 'POST' || config.method === 'PUT' ? serializedData : null;
|
|
|
|
var request = new XMLHttpRequest();
|
|
request.open(config.method, endPointUrl, config.async || true);
|
|
request.onreadystatechange = function () {
|
|
// TODO handle response properly
|
|
callback ? callback(request.responseText, request.status) : undefined;
|
|
};
|
|
request.send(postData);
|
|
}
|
|
}
|
|
}; |