I am building a website using Polymer (>= 1.2.0) based on the PSK (Polymer Starter Kit).
I am running into a (probably noob) problem with attempting to centralize and/or automatize my router configurations.
I have appended the following code to the end of the PSK's app.js
file:
//note: app.baseUrl is set by PSK's original code earlier in the file: app.baseUrl = '/';
app.routeMap = [
{name: "home", text: "Home", icon: "home", url: app.baseUrl},
{name: "about", text: "About", icon: "face", url: app.baseUrl + "about"},
{name: "portfolio", text: "Portfolio", icon: "build", url: app.baseUrl + "portfolio"},
{name: "contact", text: "Contact", icon: "mail", url: app.baseUrl + "contact"}
];
I then replaced the original routing-configuration code in routing.html
with the new version, that uses the routeMap
:
page('*', scrollToTop, closeDrawer, function (ctx, next) {
next();
});
page('/', function () {
app.route = app.routeMap[0].name;
});
page(app.routeMap[0].url, function () {
app.route = app.routeMap[0].name;
});
page(app.routeMap[1].url, function () {
app.route = app.routeMap[1].name;
});
page(app.routeMap[2].url, function () {
app.route = app.routeMap[2].name;
});
page(app.routeMap[3].url, function () {
app.route = app.routeMap[3].name;
});
//404
page('*', function () {
app.$.toast.text = 'Can\'t find: ' + window.location.href + '. Redirected you to Home Page';
app.$.toast.show();
page.redirect(app.baseUrl);
});
The above code works fine! But it breaks when I try to use a for-loop instead of hard-code:
page('*', scrollToTop, closeDrawer, function (ctx, next) {
next();
});
page('/', function () {
app.route = app.routeMap[0].name;
});
//Doesn't work with this for-loop...
for (i = 0; i < app.routeMap.length; i++) {
//debug
console.log("Registering route: " + i + " - Name: " + app.routeMap[i].name + " - URL: " + app.routeMap[i].url);
page(app.routeMap[i].url, function () {
app.route = app.routeMap[i].name;
});
}
//404
page('*', function () {
app.$.toast.text = 'Can\'t find: ' + window.location.href + '. Redirected you to Home Page';
app.$.toast.show();
page.redirect(app.baseUrl);
});
The debug console.log()
prints the items of the routeMap as expected, but the routes don't work (the page(app.routeMap[i].url, function () { /*...*/ });
part doesn't work?), and I get an Uncaught TypeError: Cannot read property 'name' of undefined
located at (anonymous function) (app/elements/routing.html:86:36)
Can anyone identify the problem here? It's probably a noob one, but it's flying straight over my head...
(I know a bit of the languages involved [HTML, CSS & JS], but this is my first time making a website, and putting that knowledge to serious use in a project, rather than in an exercise/learning-assignment)