request

method
 request() 

Option name Type Description
settings object
return object

Makes request to the server

request: function (settings) {
    var that = this;
    return new owl.Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest(),
            method = settings.type || 'GET',
            url = settings.url,
            data = settings.data,
            body = null,
            key;

        if (method === 'GET' || method === 'DELETE') {
            url += that.toQueryString(data);
        } else {
            body = that.toJsonString(data);
        }
        xhr.onreadystatechange = function() {
            var response,
                error;
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    response = JSON.parse(xhr.responseText);
                    settings.success && settings.success(response);
                    resolve(response);
                } else {
                    owl.ajax.error(xhr);
                    settings.error && settings.error(xhr, xhr.statusText);
                    error = new Error('Respond with ' + xhr.status);
                    error.status = xhr.status;
                    error.responseText = xhr.responseText;
                    error.json = JSON.parse(xhr.responseText);
                    reject(error);
                }
            }
        };
        xhr.open(method, url, true);
        for (key in _headers) {
            if (_headers.hasOwnProperty(key)) {
                xhr.setRequestHeader(key, _headers[key]);
            }
        }
        xhr.send(body);
    });
},

setHeader

method
 setHeader() 

Option name Type Description
key string
value string

Sets a header for each request

setHeader: function(key, value) {
    _headers[key] = value;
},

removeHeader

method
 removeHeader() 

Option name Type Description
key string

Removes a header

removeHeader: function(key) {
    delete _headers[key];
},

error

method
 error() 

Option name Type Description
xhr

Default event error listener

error: function(xhr) {
    console.log(xhr);
},

toQueryString

method
 toQueryString() 

Option name Type Description
data object
return string

Makes query string from data

toQueryString: function(data) {
    var query = [],
        key;
    if (!(typeof data === 'object')) {
        return data || '';
    }
    for (key in data) {
        if (data.hasOwnProperty(key)) {
            query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        }
    }
    return '?' + query.join('&');
},

toJsonString

method
 toJsonString() 

Option name Type Description
data
return string

Stringify an object

toJsonString: function(data) {
    if (!(typeof data === 'object')) {
        return data || '';
    }
    return JSON.stringify(data);
}
    };
})(owl);