23

I know meteor exposes events such as "click", for DOM element but I'm wondering if there's a load event that's fired when a template or partial is loaded? How would I accomplish this?

Thanks.

Nachiket
  • 6,021
  • 6
  • 41
  • 47
Gezim
  • 7,112
  • 10
  • 62
  • 98

3 Answers3

42

For Meteor starting from 0.4.0 preview, you can use Template.myTemplate.created.

In Template.myTemplate.created the DOM is not ready however.

If you need to manipulate the DOM, you might want to use Template.myTemplate.rendered instead and use a boolean value to track the state within the Template object like this:

Template.myTemplate.rendered = function() {
    if(!this._rendered) {
      this._rendered = true;
      console.log('Template onLoad');
    }
}
Joscha
  • 4,643
  • 1
  • 27
  • 34
  • 3
    `Template.myTemplate.rendered` is deprecated since Meteor 1.0.4. While it is still supported for backward compatibility, you may want to use `Template.myTemplate.onRendered` for newer versions. [Source](https://github.com/meteor/meteor/blob/devel/History.md#blaze-2) – clemlatz Oct 17 '15 at 13:56
11

Following should work.
Meteor.defer will get called once template is added to DOM and rendered.

<template name="temp">
    //regular stuff
    {{invokeAfterLoad}}
</template>

Template.temp.invokeAfterLoad = function () {
  Meteor.defer(function () {
     $('mydiv').jquerify();
  });
  return "";
};
Nachiket
  • 6,021
  • 6
  • 41
  • 47
5

I'd recommend this rather than the accepted answer, slightly less gross IMHO:

<template name="temp">
    {{aReactiveHelper}}
</template>

Template.temp.aReactiveHelper = function() {
  var someValue = Session.get('someValue');
  invokeAfterLoad();
  return someValue;
};

var invokeAfterLoad = function () {
  Meteor.defer(function () {
     $('mydiv').doSomething();
  });
};

The assumption is that you want to invoke something after the template loads because it's reacting to a reactive object.

The benefit here is you're not adding animation code to your template.

Mike Bannister
  • 1,424
  • 1
  • 13
  • 16