Create routes from array
rikyperdana opened this issue · 4 comments
I tried to do this in coffeescript
routes = [
'page1'
'page2'
'page3'
]
for route in routes
Router.route '/' + route,
action: -> this.render route
It returns no error, it only route to page3
And when I go to page1 or page2, it keeps rendering page3
What's wrong with my code?
why are you doing action: -> this.render route
?
It equals to
var routes;
routes = ['page1', 'page2', 'page3'];
var i, j, len;
for (j = 0, len = routes.length; j < len; j++) {
i = routes[j];
Router.route('/' + route, {
action: function() {
return this.render(i);
}
});
}
I intend to render each template in routes array
Does my codes understandable?
@rikyperdana this is happening because you're trying to set a variable in a callback function inside a loop, but js only gives you a reference... so that at the end of the loop, i
always is set to page3
wrapping it in a function forces js to evaluate the value on every tick of the loop:
for (j = 0, len = routes.length; j < len; j++) {
(function(i) {
Router.route('/' + i, function() {
this.render(i);
});
})(routes[j]);
}
but you could just do
Router.route('page1');
Router.route('page2');
Router.route('page3');
or simply
routes = [
'page1'
'page2'
'page3'
]
for route in routes
Router.route route
see the guide for more info on declaring routes: http://iron-meteor.github.io/iron-router/
Thank's a lot, you were so helpful :)