Browse Source

Replace $.get/$.post with "xr" lib

Promise-based XHR: https://github.com/radiosilence/xr
master
Chimo 6 years ago
parent
commit
6932522fdd
6 changed files with 402 additions and 44 deletions
  1. +1
    -1
      build.sh
  2. +177
    -0
      dist/extlib/xr.js
  3. +1
    -0
      examples/pois/pois.html
  4. +177
    -0
      src/extlib/xr.js
  5. +44
    -41
      src/nominatim.js
  6. +2
    -2
      src/poi.js

+ 1
- 1
build.sh View File

@ -11,4 +11,4 @@ uglifyjs --source-map "${DIR}"/chiq.map.js --screw-ie8 --mangle --compress --lin
cat src/*.js > "${DIR}"/chiq.unmin.js
# extlibs
cp src/extlib/latlon-spherical.js dist/extlib/
cp src/extlib/*.js dist/extlib/

+ 177
- 0
dist/extlib/xr.js View File

@ -0,0 +1,177 @@
// https://github.com/radiosilence/xr
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module);
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod);
global.xr = mod.exports;
}
})(this, function (exports, module) {
/**
* xr (c) James Cleveland 2015
* URL: https://github.com/radiosilence/xr
* License: BSD
*/
'use strict';
var Methods = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
PATCH: 'PATCH',
OPTIONS: 'OPTIONS'
};
var Events = {
READY_STATE_CHANGE: 'readystatechange',
LOAD_START: 'loadstart',
PROGRESS: 'progress',
ABORT: 'abort',
ERROR: 'error',
LOAD: 'load',
TIMEOUT: 'timeout',
LOAD_END: 'loadend'
};
var defaults = {
method: Methods.GET,
data: undefined,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
dump: JSON.stringify,
load: JSON.parse,
xmlHttpRequest: function xmlHttpRequest() {
return new XMLHttpRequest();
},
promise: function promise(fn) {
return new Promise(fn);
}
};
function res(xhr) {
return {
status: xhr.status,
response: xhr.response,
xhr: xhr
};
}
function assign(l) {
for (var _len = arguments.length, rs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rs[_key - 1] = arguments[_key];
}
for (var i in rs) {
if (!({}).hasOwnProperty.call(rs, i)) continue;
var r = rs[i];
if (typeof r !== 'object') continue;
for (var k in r) {
if (!({}).hasOwnProperty.call(r, k)) continue;
l[k] = r[k];
}
}
return l;
}
function urlEncode(params) {
var paramStrings = [];
for (var k in params) {
if (!({}).hasOwnProperty.call(params, k)) continue;
paramStrings.push(encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
}
return paramStrings.join('&');
}
var config = {};
function configure(opts) {
config = assign({}, config, opts);
}
function promise(args, fn) {
return (args && args.promise ? args.promise : config.promise || defaults.promise)(fn);
}
function xr(args) {
return promise(args, function (resolve, reject) {
var opts = assign({}, defaults, config, args);
var xhr = opts.xmlHttpRequest();
xhr.open(opts.method, opts.params ? opts.url.split('?')[0] + '?' + urlEncode(opts.params) : opts.url, true);
xhr.addEventListener(Events.LOAD, function () {
if (xhr.status >= 200 && xhr.status < 300) {
var _data = null;
if (xhr.responseText) {
_data = opts.raw === true ? xhr.responseText : opts.load(xhr.responseText);
}
resolve(_data);
} else {
reject(res(xhr));
}
});
xhr.addEventListener(Events.ABORT, function () {
return reject(res(xhr));
});
xhr.addEventListener(Events.ERROR, function () {
return reject(res(xhr));
});
xhr.addEventListener(Events.TIMEOUT, function () {
return reject(res(xhr));
});
for (var k in opts.headers) {
if (!({}).hasOwnProperty.call(opts.headers, k)) continue;
xhr.setRequestHeader(k, opts.headers[k]);
}
for (var k in opts.events) {
if (!({}).hasOwnProperty.call(opts.events, k)) continue;
xhr.addEventListener(k, opts.events[k].bind(null, xhr), false);
}
var data = typeof opts.data === 'object' && !opts.raw ? opts.dump(opts.data) : opts.data;
if (data !== undefined) xhr.send(data);else xhr.send();
});
}
xr.assign = assign;
xr.urlEncode = urlEncode;
xr.configure = configure;
xr.Methods = Methods;
xr.Events = Events;
xr.defaults = defaults;
xr.get = function (url, params, args) {
return xr(assign({ url: url, method: Methods.GET, params: params }, args));
};
xr.put = function (url, data, args) {
return xr(assign({ url: url, method: Methods.PUT, data: data }, args));
};
xr.post = function (url, data, args) {
return xr(assign({ url: url, method: Methods.POST, data: data }, args));
};
xr.patch = function (url, data, args) {
return xr(assign({ url: url, method: Methods.PATCH, data: data }, args));
};
xr.del = function (url, args) {
return xr(assign({ url: url, method: Methods.DELETE }, args));
};
xr.options = function (url, args) {
return xr(assign({ url: url, method: Methods.OPTIONS }, args));
};
module.exports = xr;
});

+ 1
- 0
examples/pois/pois.html View File

@ -30,6 +30,7 @@
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="../../dist/extlib/xr.js"></script>
<script src="../../dist/extlib/latlon-spherical.js"></script>
<script src="../../dist/chiq.unmin.js"></script>
<script src="js/pois.js"></script>


+ 177
- 0
src/extlib/xr.js View File

@ -0,0 +1,177 @@
// https://github.com/radiosilence/xr
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module);
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod);
global.xr = mod.exports;
}
})(this, function (exports, module) {
/**
* xr (c) James Cleveland 2015
* URL: https://github.com/radiosilence/xr
* License: BSD
*/
'use strict';
var Methods = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
PATCH: 'PATCH',
OPTIONS: 'OPTIONS'
};
var Events = {
READY_STATE_CHANGE: 'readystatechange',
LOAD_START: 'loadstart',
PROGRESS: 'progress',
ABORT: 'abort',
ERROR: 'error',
LOAD: 'load',
TIMEOUT: 'timeout',
LOAD_END: 'loadend'
};
var defaults = {
method: Methods.GET,
data: undefined,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
dump: JSON.stringify,
load: JSON.parse,
xmlHttpRequest: function xmlHttpRequest() {
return new XMLHttpRequest();
},
promise: function promise(fn) {
return new Promise(fn);
}
};
function res(xhr) {
return {
status: xhr.status,
response: xhr.response,
xhr: xhr
};
}
function assign(l) {
for (var _len = arguments.length, rs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rs[_key - 1] = arguments[_key];
}
for (var i in rs) {
if (!({}).hasOwnProperty.call(rs, i)) continue;
var r = rs[i];
if (typeof r !== 'object') continue;
for (var k in r) {
if (!({}).hasOwnProperty.call(r, k)) continue;
l[k] = r[k];
}
}
return l;
}
function urlEncode(params) {
var paramStrings = [];
for (var k in params) {
if (!({}).hasOwnProperty.call(params, k)) continue;
paramStrings.push(encodeURIComponent(k) + '=' + encodeURIComponent(params[k]));
}
return paramStrings.join('&');
}
var config = {};
function configure(opts) {
config = assign({}, config, opts);
}
function promise(args, fn) {
return (args && args.promise ? args.promise : config.promise || defaults.promise)(fn);
}
function xr(args) {
return promise(args, function (resolve, reject) {
var opts = assign({}, defaults, config, args);
var xhr = opts.xmlHttpRequest();
xhr.open(opts.method, opts.params ? opts.url.split('?')[0] + '?' + urlEncode(opts.params) : opts.url, true);
xhr.addEventListener(Events.LOAD, function () {
if (xhr.status >= 200 && xhr.status < 300) {
var _data = null;
if (xhr.responseText) {
_data = opts.raw === true ? xhr.responseText : opts.load(xhr.responseText);
}
resolve(_data);
} else {
reject(res(xhr));
}
});
xhr.addEventListener(Events.ABORT, function () {
return reject(res(xhr));
});
xhr.addEventListener(Events.ERROR, function () {
return reject(res(xhr));
});
xhr.addEventListener(Events.TIMEOUT, function () {
return reject(res(xhr));
});
for (var k in opts.headers) {
if (!({}).hasOwnProperty.call(opts.headers, k)) continue;
xhr.setRequestHeader(k, opts.headers[k]);
}
for (var k in opts.events) {
if (!({}).hasOwnProperty.call(opts.events, k)) continue;
xhr.addEventListener(k, opts.events[k].bind(null, xhr), false);
}
var data = typeof opts.data === 'object' && !opts.raw ? opts.dump(opts.data) : opts.data;
if (data !== undefined) xhr.send(data);else xhr.send();
});
}
xr.assign = assign;
xr.urlEncode = urlEncode;
xr.configure = configure;
xr.Methods = Methods;
xr.Events = Events;
xr.defaults = defaults;
xr.get = function (url, params, args) {
return xr(assign({ url: url, method: Methods.GET, params: params }, args));
};
xr.put = function (url, data, args) {
return xr(assign({ url: url, method: Methods.PUT, data: data }, args));
};
xr.post = function (url, data, args) {
return xr(assign({ url: url, method: Methods.POST, data: data }, args));
};
xr.patch = function (url, data, args) {
return xr(assign({ url: url, method: Methods.PATCH, data: data }, args));
};
xr.del = function (url, args) {
return xr(assign({ url: url, method: Methods.DELETE }, args));
};
xr.options = function (url, args) {
return xr(assign({ url: url, method: Methods.OPTIONS }, args));
};
module.exports = xr;
});

+ 44
- 41
src/nominatim.js View File

@ -1,5 +1,5 @@
( function() {
/*global Promise: false*/
/*global Promise: false, xr: false*/
"use strict";
var _Pullet = window.Pullet || {},
@ -8,16 +8,52 @@
_Pullet.nominatim = {
lookup: function( points ) {
var endpoint = window.Pullet.endpoint.nominatim + "/lookup",
query,
i,
len = points.length,
batch,
batches = [],
ids = [],
processBatch,
batchesCompleted = 0,
results = [],
origs = points.slice(); /* Make a copy of the original array since splice modifies it. TODO: Revise this. */
processBatch = function( resolve ) {
var j,
len2,
result,
index,
place;
batchesCompleted += 1;
// FIXME: technically, we could start filling Places before all
// data is received from Nominatim
if ( batchesCompleted === len ) {
len2 = results.length;
for ( j = 0; j < len2; j += 1 ) {
result = results[ j ];
// Find `Place` matching osm_id from `origs` collection
index = findPlace( result.osm_id, origs );
if ( index === false ) {
continue;
}
// Fill data
place = origs[ index ];
place.fill( result );
// Overwrite original
origs[ index ] = place;
}
resolve( origs );
}
};
return new Promise( function( resolve/*, reject*/ ) {
/* Don't contact endpoint if we have no data or bad param */
if ( !Array.isArray( points ) || points.length === 0 ) {
@ -38,48 +74,15 @@
}
for ( i = 0, len = batches.length; i < len; i += 1 ) {
query = "format=json&osm_ids=" + batches[ i ].join();
$.get( endpoint, query )
.done( function( data ) {
xr.get( endpoint, { format: "json", osm_ids: batches[ i ].join() } )
.then( function( data ) {
results = results.concat( data );
} )
.always( function() {
var j,
len2,
result,
index,
place;
batchesCompleted += 1;
// FIXME: technically, we could start filling Places before all
// data is received from Nominatim
if ( batchesCompleted === len ) {
len2 = results.length;
for ( j = 0; j < len2; j += 1 ) {
result = results[ j ];
// Find `Place` matching osm_id from `origs` collection
index = findPlace( result.osm_id, origs );
if ( index === false ) {
continue;
}
// Fill data
place = origs[ index ];
place.fill( result );
// Overwrite original
origs[ index ] = place;
}
resolve( origs );
}
processBatch( resolve );
} )
.catch( function() {
processBatch( resolve );
} );
}
} );
}


+ 2
- 2
src/poi.js View File

@ -1,5 +1,5 @@
( function() {
/*global Promise: false, Pullet: false, LatLon: false*/
/*global Promise: false, Pullet: false, LatLon: false, xr: false*/
"use strict";
var _Pullet = window.Pullet || {},
@ -137,7 +137,7 @@
"</osm-script>";
// Fetch POIs
return $.post( endpoint, xml )
return xr.post( endpoint, xml )
.then( function( data ) {
var elms = data.elements,
len = elms.length,


Loading…
Cancel
Save