back to devpro   download
// on the server: StaticJSONP.notify("unique_request_id", {the:response_data});
var StaticJSONP = (function (window) {//"use strict"; // if you want ...
    
    // (C) WebReflection - Mit Style License
    
    var // minifier friendly shortcuts
        document = window.document,
        documentElement = document.documentElement,
        
        // notifications container
        results = {},
        
        // just to keep script size as small as possible
        i, script
    ;
    
    // whenever the server replies or not
    // try to keep the DOM as clear as possible
    function removeScript() {
        script = this;
        script.parentNode === documentElement && documentElement.removeChild(script);
    }
    
    return {
        
        // when StaticJSONP.notify(uid, data) is invoked
        notify: function notify(uid, data) {
            // loop over all registered callbacks
            for (i = 0, script = results[uid]; i < script.length; i++) {
                // be sure other listeners are not
                // affected by a single listener failure
                // (for whatever external reason)
                try {
                    script[i](uid, data);
                } catch(_) {
                    // none of this script business
                    // just keep notifying
                }
            }
            // delete this uid so that next call
            // will be performed in any case
            delete results[uid];
        },
        
        // a request may take time
        // this method prevent multiple requestes for same uid
        // until the request has not been evaluated
        // StaticJSONP.request(url, callback);
        // StaticJSONP.request(url, uid, callback);
        request: function request(uri, uid, callback) {
            if(!callback) {
                callback = uid;
                uid = uri;
            }
            // if nobody asked for this uid
            if (!(uid in results)) {
                // create the notification stack
                results[uid] = [];
                // append and load the script
                script = documentElement.insertBefore(
                    document.createElement("script"),
                    documentElement.lastChild
                );
                script.onload = script.onerror = removeScript;
                script.src = uri;
            }
            // add notification callback
            results[uid].push(callback);
        }
    };
    
}(this));
back to devpro   download
Creative Commons License