渲染流星模板后运行 JS [英] Run JS after rendering a meteor template

查看:39
本文介绍了渲染流星模板后运行 JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的模板:

I have a template that looks something like this:

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

我渲染它:

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

我有一些事件处理程序:

And I have some event handlers:

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

我想要做的是根据其内容的大小设置 textarearows 属性.我意识到我可以编写一个 Handlebars 助手,但它无法访问正在呈现的 DOM 元素,这将迫使我进行一些不必要的复制.理想情况下,我想要的是流星在呈现元素后触发事件.类似的东西:

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
}

这可能吗?

推荐答案

我认为目前最好"的方式来做到这一点(这有点像黑客)是使用 Meteor.defer ala在 Meteor.js 中更新 DOM 后的回调.

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 是流星开发者之一,所以他的话是福音:)

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>

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

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

   return this.uuid;
 }

编辑

请注意,作为 0.4.0,您可以以一种非常特别的方式执行此操作(如 Sander 所指出的):

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();
}

这篇关于渲染流星模板后运行 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆