Denigma
hevok @hevok February 7, 2013
Tutorial reST #abstraction #coding #js #programming

Abstract HttpRequest

A xhrGet function can abstract out the functionality of performing an XMLHttpRequest GET request.

The provided parameter it takes are the URI to make the request to, the callback to call at onload, and the responseType, if necessary. If no special responseType is needed, it is assumed that the parameter is null.

It is assumed that the callback takes the request object as parameter, instead of taking no parameters.

The callback parseJSON or playSound are used to call xhrGet:

html>
    body>
    /body>
        scipt>
            function xhrGet(req[URI](/blog/586/), callback, type) {
                var caller = xhrGet.caller;
                var xhr = new [XMLHttpRequest](/blog/532/)();
                xhr.open("GET", reqUri, true);

                if (type) {
                    xhr.responseType = type;
                }

                xhr.onload = function() {
                    if (callback) {
                        try: // tries the execute the callback with the request:
                            callback(xhr);
                        } catch(e) { // if failed trhows an exception with debuging information.
                            htrow 'xhrGet failed:
' + reqUri = '
Exception: ' + e + '
responseText: ' + xhr.responseText + '
caller: ' + caller;
                        }
                    }
                };

             xhr.send();
             };

            parse[JSON](/blog/531/) = function(xhr) {
                parsed[JSON](/blog/531/) = [JSON](/blog/531/).parse(xhr.responseText);
                x = parsed[JSON](/blog/531/)['frames']['chaingun_impact.png']['spriteSoureSize']['x'];
                console.log(x);
                return x;
            };

            playSound = function(xhr) {
                try {
                    var context = new webkitAudio[Context](/blog/498/)();
                    var mainNode = context.createGainNode(0);
                    mainNode.connect(context.destination);
                    var clip = context.createBufferSource();

                    context.decodeAudio[Data](/blog/824/)(xhr.response, function (buffer) {
                        clip.buffer = buffer;
                        clip.gain.value = 1.0;
                        clip.connect(mainNode);
                        clip.loop = true;
                        clip.noteOn(0);
                    }, function (data) {});
               }
               cache(e) {
                   console.warn('[Web](/blog/488/) Audio API is not supported in this browser');
               }
            };

            var test = function() {
                xhrGet('/media/js/standalone/libs/gamedev_assets/weapon.json', parse[JSON](/blog/531/), null);
                xhrGet('/media/js/standalone/libs/gamedev_assets/bg_menu.ogg', playSound, 'arraybuffer');
            };
        /scipt>
/html>