Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run JS after rendering a meteor template

Tags:

meteor

I have a template that looks something like this:

<template name="foo">
  <textarea name="text">{{contents}}</textarea>
</template>

I render it with:

Template.foo = function() {
  return Foos.find();
}

And I have some event handlers:

Template.foo.events = {
  'blur textarea': blurHandler
}

What I want to do is set the rows attribute of the textarea depending on the size of its contents. I realize that I could write a Handlebars helper, but it wouldn't have access to the DOM element being rendered, which would force me to do some unnecessary duplication. What I want, ideally, is for meteor to trigger an event after an element is rendered. Something like:

Template.foo.events = {
  'render textarea': sizeTextarea
}

Is this possible?

like image 834
Trevor Burnham Avatar asked Jun 13 '12 19:06

Trevor Burnham


2 Answers

As of Meteor 0.4.0 it is possible to check if a template has finished rendering, see http://docs.meteor.com/#template_rendered

If I understand your question correctly, you should wrap your textarea resize code inside a Template.foo.onRendered function:

Template.foo.onRendered(function () {
  this.attach_textarea();
})
like image 165
Sander van den Akker Avatar answered Sep 22 '22 11:09

Sander van den Akker


I think the current 'best' way to do this (it's a bit of a hack) is to use Meteor.defer ala Callback after the DOM was updated in Meteor.js.

Geoff is one of the meteor devs, so his word is gospel :)

So in your case, you could do something like:

 <textarea id="{{attach_textarea}}">....</textarea>

and

 Template.foo.attach_textarea = function() {
   if (!this.uuid) this.uuid = Meteor.uuid();

   Meteor.defer(function() {
     $('#' + this.uuid).whatever();
   });

   return this.uuid;
 }

EDIT

Note, that as 0.4.0, you can do this in a much ad-hoc way (as pointed out by Sander):

Template.foo.rendered = function() {
  $(this.find('textarea')).whatever();
}
like image 43
Tom Coleman Avatar answered Sep 21 '22 11:09

Tom Coleman