JSFiddle - React, Tailwind, and code Playground
by Roman Zhak
JavaScript
var ajax_cache = {};
function xhr( options ) {
options = options || {};
// retrieve data
var url = options.url
, res = {success: null}
, pub = {
on : function( type, fn ) {
if(!res[type]) res[type] = fn;
}
};
if(!ajax_cache[url]) {
ajax_cache[url] = {};
}else {
setTimeout(function() {
res.success.call( this, ajax_cache[url] )
}, 0);
return pub;
}
var req = new XMLHttpRequest;
req.open( options.method || "GET", options.url, options.async || true);
req.onreadystatechange = function() {
if( req.readyState === 4 ) {
var response;
(response = [])
.push( JSON.parse(req.responseText) ,
req.getAllResponseHeaders())
if( res.success ) {
res.success.call( this, {
data : response,
date : new Date,
type : "raw"
});
// store data
ajax_cache[url].data = response;
ajax_cache[url].date = new Date;
ajax_cache[url].type = "cache";
}
}
};
req.send( options.data || null );
return pub;
};
xhr({url: "/echo/json/"}).on("success", function() {
console.log.apply( console, arguments );
xhr({url: "/echo/json/"}).on("success", function( data ) {
console.log( data )
});
});