I'm working on an app that downloads some SVG paths from a server and draws them.
Anything in here is open to critique, but specifically I'd like to review my use of a module pattern and my implementation and use of promise objects.
The "modules" are each a file, and the aim is to limit and explicitly declare dependencies. My use of promises is to simplify the use of ajax.
My 3 files are:
- init.js - the main application.
- promise.js - my implementation of promises
- ajax.js - ajax functionality
init.js:
(function (window, document, bigmap, ajax) {
"use strict";
var attr = {
fill: "#fafafa",
stroke: "#505050",
"stroke-width": 1,
"stroke-linejoin": "round"
};
var drawings, svg_canvas;
svg_canvas = bigmap.initialize("map", window.innerWidth - 21, window.innerHeight - 21);
ajax.post("php/paths.php", null)
.then(function (value) { drawings = JSON.parse(value); })
.then(function () { bigmap.draw(svg_canvas, drawings.walls, null); })
.then(function () { bigmap.draw(svg_canvas, drawings.depts, attr); });
}(this, this.document, parent.bigmap, parent.ajax));
promise.js:
var promise = function () {
"use strict";
var pending = [],
ready = false,
result;
var then = function (callback) {
if (typeof callback === "function") {
if (ready === false) {
pending.push(callback);
} else {
callback(result);
}
}
return this;
};
var keep = function (response) {
if (ready === false) {
ready = true;
pending.forEach(function (value, index, ar) {
result = response;
value(result);
});
pending = undefined;
}
};
var isReady = function () {
return ready;
};
return {
keep: keep,
share: {
then: then,
isReady: isReady
}
};
};
ajax.js:
var ajax = (function (XMLHttpRequest, promise) {
"use strict";
var done = 4, ok = 200;
function post(url, parameters) {
var XHR = new XMLHttpRequest();
var p = promise();
if (parameters === false || parameters === null || parameters === undefined) {
parameters = "";
}
XHR.open("post", url, true);
XHR.setRequestHeader("content-type", "application/x-www-form-urlencoded");
XHR.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
XHR.onreadystatechange = function () {
if (XHR.readyState === done && XHR.status === ok) {
p.keep(XHR.responseText);
}
};
XHR.send(parameters);
return p.share;
}
return {
post: post
};
}(parent.XMLHttpRequest, parent.promise));
Thanks.
then
as variable names. Most browsers will be ok with it, but it's by no means guaranteed. \$\endgroup\$then
is not a reserved word in javascript. \$\endgroup\$