Skip to content

Instantly share code, notes, and snippets.

@jonchretien
Last active October 13, 2015 23:07
Show Gist options
  • Save jonchretien/4269805 to your computer and use it in GitHub Desktop.
Save jonchretien/4269805 to your computer and use it in GitHub Desktop.
Parser that extracts region names from data stream and pushes to sorted array.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Region Parser</title>
<meta charset="UTF-8">
</head>
<body>
<button id="js-button">Filter Data</button>
<ol id="js-container"></ol>
<script src="../js/app.js"></script>
<script>
window.addEventListener('DOMContentLoaded', APP.RegionParser.init('GB'), false);
</script>
</body>
</html>
/**
* @author Jon Chretien
* @overview Parser that extracts region names from data stream and pushes to sorted array
* @param {string} Country code
* @param {object} Optional object that overwrites defaults
*/
(function() {
'use strict';
// global namespace
var APP = window.APP = {};
APP.RegionParser = {
defaults: {
button: 'js-button',
container: 'js-container'
},
init: function(country, options) {
// declare vars
this.country = country;
// provide for custom options via init()
this.options = {};
for ( var prop in this.defaults ) {
if ( this.defaults.hasOwnProperty(prop) ) {
this.options[ prop ] = this.defaults[ prop ];
}
}
for ( prop in options ) {
if ( options.hasOwnProperty(prop) ) {
this.options[ prop ] = options[ prop ];
}
}
// cache DOM elements
this.button = document.getElementById(this.options.button);
this.container = document.getElementById(this.options.container);
// run app
this.run();
},
run: function() {
this.setEventHandlers();
},
setEventHandlers: function() {
this.button.addEventListener('click', this.makeAjaxRequest.bind(this), false);
},
makeAjaxRequest: function(event) {
var self = this;
// disable button
event.currentTarget.setAttribute('disabled', 'disabled');
// make HTTP request
var url = '../data/' + this.country + '.json';
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url);
httpRequest.onreadystatechange = function() {
if ( httpRequest.readyState === 4 && httpRequest.status === 200 ) {
var data = JSON.parse(httpRequest.responseText);
self.parseData(data);
}
};
httpRequest.send();
},
parseData: function(data) {
var regions = [];
for ( var key in data ) {
if ( data.hasOwnProperty(key) ) {
regions.push( Object.keys( data[key].region ) );
}
}
regions.sort();
this.insertResults(regions);
},
insertResults: function(filteredData) {
var fragment = document.createDocumentFragment();
var len = filteredData.length;
for ( var i=0; i < len; i++ ) {
var el = document.createElement('li');
if ( i === 0 ) {
el.innerHTML = '&lt;none&gt;';
} else {
el.innerHTML = filteredData[i];
}
fragment.appendChild(el);
}
this.container.appendChild(fragment);
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment