Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback after the DOM was updated in Meteor.js

Tags:

meteor

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?

like image 317
Johannes Fahrenkrug Avatar asked Apr 11 '12 16:04

Johannes Fahrenkrug


1 Answers

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.

like image 168
Geoff Avatar answered Sep 17 '22 20:09

Geoff