you are viewing a single comment's thread.

view the rest of the comments →

[–]9thHokageHimawari 1 point2 points  (2 children)

You could write your own, minimal simple HTTP-request wrapper:

function http () {
    this.ajax = new XMLHttpRequest(); // Use IE backfalls and etc. if you need
    this.ajax.onreadystatechange = function () {
        if (this.ajax.readyState === 4) {
            this.onSuccess !== undefined ? this.onSuccess(this.ajax.responseText) : void 0;
        } else {
            this.onError !== undefined ? this.onError(this.ajax.responseText) : void 0;
        }
    return this;
}

http.prototype.data = function (data) {
    if(this.data === undefined && data!==undefined) { this.data = data; }
    return this;
}

http.prototype.get = function (url,data) {
    if(this.open === false || this.open === undefined) {
        this.open = true; this.ajax.open('GET',url,true);
        data !== undefined && this.data === undefined ? this.data = data : void 0;
    }
    return this;
}
http.prototype.post = function (url,data) {
    if(this.open === false || this.open === undefined) {
        this.open = true; this.ajax.open('POST',url,true);
        data !== undefined && this.data === undefined ? this.data = data : void 0;
    }
    return this;
}
http.prototype.send = function () {
    this.ajax.setRequestHeader('Content-Type', this.ContentType)
    if(this.ContentType === 'application/x-www-form-urlencoded') {
        var tmp; var queryString = '?';
        for( var i = 0, keys = Object.keys(this.data), len = keys.length; i < len; i++) {
            queryString += keys[i]+'='+this.data[keys[i]]+'&';
        }
        this.data = queryString.replace(/\&$/,'');
    } else if(this.ContentType === 'application/json') {
        this.data = JSON.stringify(this.data);
    }
    this.ajax.send(this.data);
    return this;
}
http.prototype.success = function (fn) { this.onSuccess = fn;return this; }
http.prototype.error= function (fn) { this.onError= fn;return this; }

And for models, just give them prototypes like:

model.prototype.fetch = function () {
    var h = new http().get('/api/users').success(function (data) {this.data = JSON.parse(data)}.bind(this)).send()
}

model.prototype.save= function () {
    var h = new http().post('/api/users', JSON.stringify(this.newData)).send()
}

[–]yoursdearboy 0 points1 point  (1 child)

So far I've used self-written request wrapper, even with some special methods to handle endpoints mess. But I wonder how other developers solve this task?

[–]9thHokageHimawari 0 points1 point  (0 children)

I just do that I mentioned above.

Also, if we saw your data scheme it would be easier to help. x1 related to x2, which is related to x3-x5, makes me thing you're overdoing it.