Run JS after rendering a meteor template

2020-06-13 04:56发布

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?

标签: meteor
4条回答
霸刀☆藐视天下
2楼-- · 2020-06-13 05:20

Yeah I think so - not sure if it's "the right way", but this works for me:

In your app JS, the client section will run whatever javascript there on the client. For example:

if (Meteor.is_client) {
    $(function() {
        $('textarea').attr('rows' , 12) // or whatever you need to do
    })
    ...

Note the example here uses JQuery, in which case you need to provide this to the client (I think :-). In my case:

I created a /client dir, and added jquery.js file under this.

Hope this helps.

查看更多
神经病院院长
3楼-- · 2020-06-13 05:24

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();
})
查看更多
我命由我不由天
4楼-- · 2020-06-13 05:26

Since about June 2014, the correct way to do this has been to set a callback using Template.myTemplate.onRendered() .

查看更多
老娘就宠你
5楼-- · 2020-06-13 05:39

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();
}
查看更多
登录 后发表回答