JSFiddle - React, Tailwind, and code Playground
by darcyclarke
HTML
<div class="loader">Processing Request</div>
<pre class="data"></pre>
CSS
.loader {
display: none;
}
JavaScript
///////////////////////////////////////
// Plugins
///////////////////////////////////////
//
// Array Remove - By John Resig (MIT Licensed)
// http://ejohn.org/blog/javascript-array-remove/
//
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
///////////////////////////////////////
// Bare Bones Application
// Based on - http://darcyclarke.me/development/javascript-applications-101/)
///////////////////////////////////////
var $ = jQuery, App = {};
App.cache = {},
App.ajax_queue = [];
//
// Basic PubSub
//
App.publish = function(topic, args){
App.cache[topic] && $.each(App.cache[topic], function(){
this.apply($, args || []);
});
},
App.subscribe = function(topic, callback){
if(!App.cache[topic]){
App.cache[topic] = [];
}
App.cache[topic].push(callback);
return [topic, callback];
},
App.unsubscribe = function(handle){
var t = handle[0];
App.cache[t] && $.each(App.cache[t], function(idx){
if(this == handle[1]){
App.cache[t].splice(idx, 1);
}
});
},
//
// Custom AJAX function that queues / dequeues requests
//
App.ajax = function(options){
App.publish("request_init");
var jqxhr = $.ajax(options)
.success(function(){
App.ajax_queue.remove(this);
App.publish("request_destroy");
})
.error(function(){
App.ajax_queue.remove(this);
App.publish("request_destroy");
})
.complete(function(){
App.ajax_queue.remove(this);
App.publish("request_destroy");
})
.done(function(){
App.ajax_queue.remove(this);
App.publish("request_destroy");
}),
id = App.ajax_queue.push(jqxhr)-1;
return App.ajax_queue[id];
};
//
// Example: Bind subscriptions to "request_init"...