Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a XMLHttpRequest wrapper/proxy?

These methods that come to mind, what are the pros and cons of each?

Method 1: Augment native instance

var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
    var xhr = new _XMLHttpRequest();

    // augment/wrap/modify here
    var _open = xhr.open;
    xhr.open = function() {
        // custom stuff
        return _open.apply(this, arguments);
    }

    return xhr;
}

Method 2: Sub-"class" native XMLHttpRequest

var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
    // definePropertys here etc
}

XMLHttpRequest.prototype = new _XMLHttpRequest());
// OR
XMLHttpRequest.prototype = Object.create(_XMLHttpRequest);

// custom wrapped methods on prototype here
XMLHttpRequest.prototype.open = function() {
    // custom stuff
    return _XMLHttpRequest.prototype.open.apply(this, arguments);
}

Method 3: Full proxy to native XMLHttpRequest

var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
    this.xhr = new _XMLHttpRequest();
}

// proxy ALL methods/properties
XMLHttpRequest.prototype.open = function() {
    // custom stuff
    return this.xhr.open.apply(this.xhr, arguments);
}
like image 891
tlrobinson Avatar asked Jan 26 '11 19:01

tlrobinson


1 Answers

Depending on the JS engine, method 1 produces considerable overhead, since xhr.open is redefined whenever XHR is instantiated.

Method 2 makes me think "why would you need the new _XMLHttpRequest in the first place"? There's a minor feeling of undesired side effects, but it appears to work just fine.

Method 3: simple, old-school, but it won't work straight-away. (Think about reading properties)

In general, I'm personally reluctant when it comes to overwriting browser objects, so that would be a big con to all three methods. Better use some other variable like ProxyXHR (just my 2 cents)

like image 127
user123444555621 Avatar answered Oct 09 '22 01:10

user123444555621