iron-meteor / iron-router

A client and server side router designed specifically for Meteor.
MIT License
1.98k stars 413 forks source link

Create routes from array #1575

Closed rikyperdana closed 7 years ago

rikyperdana commented 7 years ago

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?

chrisbutler commented 7 years ago

why are you doing action: -> this.render route ?

rikyperdana commented 7 years ago

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?

chrisbutler commented 7 years ago

@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/

rikyperdana commented 7 years ago

Thank's a lot, you were so helpful :)