I am using a JS router for my new website project. The router accepts an object: the Key is the URL address and the Value is a function that will get called when the address is reached.
It gets messy pretty quickly with the amount pages and sub pages growing bigger and bigger, especially considering that different pages need to call different initialization functions (initAccordion or initDataTables, etc, etc).
Just to keep it neat I thought of creating an array of objects that will hold the page names and the init functions that need to be called after the page is loaded. However the solution I use uses eval:
function initFoo() {
console.log("initFoo says hi");
}
function initBar() {
console.log("initBar says hi");
}
var pages = [
{
name: "home",
init: ["initFoo", "initBar"]
},
{
name: "people",
init: ["initBar"]
}
];
var routerPaths = {};
for (var page in pages) {
var url = pages[page].name;
var init = pages[page].init;
// construct the string for eval()
var objStr = "routerPaths['" + url + "'] = function() {";
for(var item in init) {
objStr += init[item] + "();";
}
objStr += "};";
eval(objStr);
}
routerPaths.home(); // as expected: initFoo says hi initBar says hi
routerPaths.people(); // as expected: initBar says hi
This all fine, but is there a way to perhaps have the pages.init array without the quotes and the object creator NOT using eval? So that the values would look like this init: [initFoo, initBar].
So my questions really are: Is there a way of creating the new routerPaths object without constructing a string and then running eval on it? Should I just stick with what I have?
Keep in mind that routerPaths.home, routerPaths.people need to be functions that call the functions from pages.init.