Files
OfficialSite/assets/scripts/App.js

120 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-12-07 16:50:04 -05:00
/* jshint esnext: true */
import globals from './utils/globals';
2016-03-16 12:11:23 -04:00
import * as modules from './modules';
2016-03-11 09:47:43 -05:00
class App {
constructor() {
this.modules = modules;
this.currentModules = [];
}
/**
* Execute global functions and settings
* @return {Object}
*/
2016-03-11 09:47:43 -05:00
initGlobals() {
globals();
return this;
}
2016-03-09 13:22:19 -05:00
/**
* Find modules and initialize them
* @return {Object} this Allows chaining
2016-03-09 13:22:19 -05:00
*/
2016-03-11 09:47:43 -05:00
initModules() {
2016-03-09 13:22:19 -05:00
// Elements with module
var moduleEls = document.querySelectorAll('[data-module]');
2016-03-09 13:22:19 -05:00
// Loop through elements
var i = 0;
var elsLen = moduleEls.length;
2016-03-09 13:22:19 -05:00
for (; i < elsLen; i++) {
// Current element
let el = moduleEls[i];
// All data- attributes considered as options
let options = this.getElemData(el);
// Add current DOM element and jQuery element
2016-03-09 13:22:19 -05:00
options.el = el;
options.$el = $(el);
// Module does exist at this point
let attr = options.module;
// Splitting modules found in the data-attribute
let moduleIdents = attr.replace(/\s/g, '').split(',');
2016-03-09 13:22:19 -05:00
// Loop modules
let j = 0;
let modulesLen = moduleIdents.length;
for (; j < modulesLen; j++) {
let moduleAttr = moduleIdents[j];
if (typeof this.modules[moduleAttr] === 'function') {
2016-03-09 13:22:19 -05:00
let module = new this.modules[moduleAttr](options);
this.currentModules.push(module);
}
}
}
2016-03-09 13:22:19 -05:00
return this;
}
2015-08-06 13:50:19 -04:00
2016-03-09 13:22:19 -05:00
/**
* Get element data attributes
* @param {DOMElement} el
* @return {Array} data
2016-03-09 13:22:19 -05:00
*/
2016-03-11 09:47:43 -05:00
getElemData(el) {
2016-03-09 13:22:19 -05:00
// All attributes
var attributes = el.attributes;
2016-03-09 13:22:19 -05:00
// Regex Pattern
var pattern = /^data\-(.+)$/;
2016-03-09 13:22:19 -05:00
// Output
var data = {};
2016-03-09 13:22:19 -05:00
for (let i in attributes) {
2016-07-14 14:23:46 -04:00
if (!attributes[i]) {
continue;
}
2016-03-09 13:22:19 -05:00
// Attributes name (ex: data-module)
let name = attributes[i].name;
// This happens.
if (!name) {
continue;
}
let match = name.match(pattern);
if (!match) {
continue;
}
// If this throws an error, you have some
// serious problems in your HTML.
data[match[1]] = el.getAttribute(name);
2016-03-09 13:22:19 -05:00
}
return data;
}
/**
* Initialize app after document ready
*/
init() {
this.initGlobals().initModules();
}
}
2015-08-06 13:50:19 -04:00
$(function() {
window.app = new App();
window.app.init();
});