How do I pass a function to the Meteor template?

I want to insert a Meteor template (simple login form), but I want to control what happens after the form is submitted. Ideally, I would like to pass template afterLogin()

to template. But I am completely unsure how to do this, and if it is possible.

I recently saw an interesting package viewmodel

and I'm not sure how much related it is. But the goal in this context is mainly to render a view with a different view model.

Any ideas? I am currently using a session variable and then after logging in, I check that session variable to run the correct function, but this is ugly and not easy to work with. Any ideas?


source to share

2 answers

This is how I do it:

I am assuming your login form is being called from the parent template, use the attribute syntax to pass the value of the custom helper in the context of the login form data.

<template name="parent">
  {{> loginForm options=loginFormOptions}}


The helper returns an object that encapsulates the function, the caller is responsible for setting this function to whatever they want.

    return {
        // we assert that the context is correct :
        // this will print Template.loginForm


Your login form code, acting as a library, can read from the data context the function that was passed by the caller template, and then call the function with the appropriate context this

    // ...
      // guard against the existence of the custom afterLogin function
      if( &&{
        // execute the custom function with proper context;




First of all, I would use Iron Router to navigate the various views of my application, you can get it here:

meteor add iron:route


Then check out . I would use something like:{
  'click .loginButton': function() {
    //... if success login ...


[Update 1]

I am afraid that trying to pass a Route function is an ugly approach in terms of the Meteor architecture.

You can try by specifying some global variable that is responsible for listening and forwarding events along routes.

var eventHelper = (function () {
    var self = _.extend({
        afterLogin: function () {
        }}, Backbone.Events);

    return self;
    'click': function () {
        //... Let call after login

eventHelper.on('forwardedEvent',function() {
   // ... 




All Articles