js中更新DOM之后的回调

js中更新DOM之后的回调

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

问题描述

我有这个流星项目: 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.

我想在代码更改后自动运行HighlightSyntax函数,但实际上并没有用.

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

我尝试过query.observe,但是效果不是很好:语法高亮显示一次,然后再次消失.

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

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

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

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

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.

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

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

因此,呈现模板时,不能100%保证它会最终出现在DOM中.这取决于模板的用户.

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之后的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:50