Search code examples
javascriptmeteoriron-router

I'm using iron:router v1.0.7 but this.render() is "undefined". I can't see what I'm doing wrong


I'm displaying an access denied template when the visitor tries to visit the Submit page. This works fine. Here is the code:

Router.route('/', {name: 'etoeventsList'});
Router.route('/submit', {name: 'etoeventSubmit'});

var requireLogin = function () {
  if (!Meteor.user()) {
    this.render('accessDenied');
  } else {
    this.next();
  }
};

Router.onBeforeAction(requireLogin, {only: 'etoeventSubmit'});

I want to utilize "requireLogin" under a different context (anonymous user visiting '/') so I thought I would add an argument to allow me to pass in the template to be rendered. Like this:

var requireLogin = function (template) { // now with argument 'template'
  if (!Meteor.user()) {
    this.render(template); // using 'template'
  } else {
    this.next();
  }
};

Router.onBeforeAction(requireLogin('accessDenied'), {only: 'etoeventSubmit'}); // passing 'accessDenied'
Router.onBeforeAction(requireLogin('index'), {only: 'etoeventsList'}); // passing 'index'

The error I receive is Uncaught TypeError: undefined is not a function and the template I want to show does not display.


Solution

  • You can't do it that way. The way you are doing it, this will refer to Window. You will have to use an anonymous function as a param to onBeforeAction.

    Router.configure({
        layoutTemplate: 'layout',
        loadingTemplate: 'loading',
        notFoundTemplate: 'notFound',
        waitOn: function() {
    
        }
    });
    
    if(Meteor.isClient) {
      Router.onBeforeAction(function() {
        // is user logged in
        if (! Meteor.user()) {
          if (Meteor.loggingIn()) {
            this.render('loading');
          } else {
            this.render('accessDenied');
          }
        } else {
          this.next();
        }
      });
    }