本文介绍了在 Meteor.js 中更新 DOM 后的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 Meteor 项目:https://github.com/jfahrenkrug/code_buddy

它基本上是一个带有大文本区域和预区域的工具,可让您输入源代码片段,这些片段会自动推送到所有连接的客户端.

我想在更改代码时自动运行 highlightSyntax 函数,但它并没有真正起作用.

我试过 query.observe,但效果不太好:语法高亮闪过一次然后又消失了.

所以我的问题是:如何在 DOM 更新后运行代码?

解决方案

一个 hacky 的方法是:

foo.html

<div id="my-magic-div">.. 东西在这里..{{add_my_special_behavior}}

foo.js

Template.mytemplate.add_my_special_behavior = function () {流星.延迟(函数(){//在 DOM 中找到 #my-magic-div//对它做一些事情});//什么都不返回};

该函数将在模板渲染(或重新渲染)时被调用,因此您可以将其用作挂钩来执行您想做的任何特殊 DOM 操作.您需要使用 Meteor.defer(其作用与 settimeout(f, 0) 相同),因为在渲染模板时,它还不在 DOM 中.

请记住,您可以渲染模板而无需将其插入 DOM!例如,这样做是完全合法的:

console.log(Template.mytemplate())

因此,当一个模板被渲染时,并不能 100% 保证它最终会出现在 DOM 中.这取决于模板的用户.

I have this Meteor project: https://github.com/jfahrenkrug/code_buddy

It's basically a tool with a big textarea and a pre area that lets you enter source code snippets that automatically get pushed to all connected clients.

I'd like to automatically run the highlightSyntax function when the code was changed, but it doesn't really work.

I've tried query.observe, but that didn't work too well: The syntax highlight flashed up once and then disappeared again.

So my question is: How do I run code after the DOM was updated?

解决方案

A hacky way to do it is:

foo.html

<template name="mytemplate">
  <div id="my-magic-div">
    .. stuff goes here ..
    {{add_my_special_behavior}}
  </div>
</template>

foo.js

Template.mytemplate.add_my_special_behavior = function () {
  Meteor.defer(function () {
    // find #my-magic-div in the DOM
    // do stuff to it
  });
  // return nothing
};

The function will get called whenever the template is rendered (or re-rendered), so you can use it as a hook to do whatever special DOM manipulation you want to do. You need to use Meteor.defer (which does the same thing as settimeout(f, 0)) because at the time the template is being rendered, it isn't in the DOM yet.

Keep in mind that you can render a template without inserting it in the DOM! For example, it's totally legal to do this:

console.log(Template.mytemplate())

So when a template is rendered, there is not a 100% guarantee that it is going to end up in the DOM. It's up to the user of the template.

这篇关于在 Meteor.js 中更新 DOM 后的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:11