Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/**
* Polyfill for missing window.DOMParser on CocoonJS. Once you have this file in your dependency list,
* all you need to do is CocoonJS check in your main application file, eg:
*
* in app.js/index.js/main.js
*
* var GameSpace = {};
* window.onload = function() {
* if (navigator.isCocoonJS) {
* window.DOMParser = GameSpace.DOMishParser;
* }
* ...
*
* And that's it. You're more than welcome to check my blog at http://likeadev.com
*/
GameSpace.DOMishParser = function DOMishParser() {
// Empty
};
GameSpace.DOMishParser.prototype = (function() {
// DOMish attributes object
function DOMishAttributes() {};
DOMishAttributes.prototype = {
getNamedItem: function(name) {
return {
nodeValue: this[name] || null
};
}
};
// The actuall data parser
function DOMishObject(data) {
this.attributes = this.convertContent(data);
this.length = Object.keys(this.attributes).length;
}
DOMishObject.prototype = {
documentElement: document,
convertContent: function(obj) {
var attributes = new DOMishAttributes(),
prop;
for (prop in obj) {
if (obj[prop] !== null && typeof obj[prop] === 'object') {
attributes[prop] = Array.isArray(obj[prop]) ?
obj[prop].map(makeDOMishObject) : makeDOMishObject(obj[prop]);
} else {
attributes[prop] = obj[prop];
}
}
return attributes;
},
getElementsByTagName: function(name) {
return this.attributes[name] ?
Array.isArray(this.attributes[name]) ?
this.attributes[name] : [this.attributes[name]] : [];
},
getAttribute: function(name) {
return this.attributes[name];
}
};
// DOMish object creator - exists due to the fact that it's passed
// by reference in DOMishObject.convertContent
function makeDOMishObject(data) {
return new DOMishObject(data);
}
return {
parseFromString: function(data) {
return makeDOMishObject(JSON.parse(data));
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment