Meteor Template Events

meteor-templating

How can we register a template event handler?

Template.templateName.events({
  'submit form': function(event, instance) {
  }
});

In the above code, 'submit' is the event type, and 'form' is a CSS selector. Another example can be something like 'click .className'. The event handler receive 2 parameters. The first is the event object, and the second parameter is the template instance that this event handler is triggered from.

How can our event handler prevent the default behavior?

Call preventDefault():

Template.templateName.events({
  'eventType cssSelector': function(event, instance) {
    event.preventDefault();
  }
});

How can our event handler determine the type of the event?

Use .type:

Template.templateName.events({
  'eventType cssSelector': function(event, instance) {
    alert(event.type);
  }
});

How can we run a function when the template is created?

Register an onCreated handler:

Template.templateName.onCreated(function(){
  // Whatever code you need to run
});

How can we run a function when the template is rendered?

Register an onRendered handler:

Template.templateName.onRendered(function(){
  // Whatever code you need to run
});

How can we run a function when the template is destroyed?

Register an onDestroyed handler:

Template.templateName.onDestroyed(function(){
  // Whatever code you need to run
});

How can we run a function whenever a template is re-rendered?

In my limited experience with Meteor, it seems that the onRendered event is only triggered once, and if the template is re-rendered, the onRendered event is not triggered. Maybe the template is not re-rendered, but it just re-drawn because it is "reactive".

What is the purpose of the this keyword inside the onCreated event handler?

Inside the onCreated event handler, the this keyword represent the template instance. This is true for onRendered and onDestroyed handlers as well.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License