Execute jQuery code when template updates



I believe this question is already asked & answered, but I couldn’t find a solution:

I got in template:

{{#if someCondition}}
  <div class="blahblah"></div>

I want to execute jQuery code on div when it’s shown (when it appears in DOM).

Trivial solution is to add code in “someCondition” helper, but I got ~30 templates with 2-3 similar cases each, and I wish if I could make this with one shot instead refactoring entire program.

Is there some jQuery.live or another trick, or UI.onUpdate thing or something that will help me?

Example I wrote is trivial - what I want is in fact execute FlatUI radio button initialization code, something like $("input[type='radio']").radiocheck();

Thanks for help!


The easiest way to do this is to put the code into a new template:

{{#if someCondition}}
  {{> blahblah}}

<template name="blahblah">
  <div class="blahblah"></div>

And then use the rendered callback:

Template.blahblah.rendered = function () {

In this case, you could make a FlatUI radio button template.


Thanks sashko! :slight_smile: But, your solution requires refactoring entire program, is there some “shortcut” - observing DOM changes and exec. code when template block is shown?


There’s also an undocumented feature called _uihooks. You can read about it in the sketchy email thread here: https://groups.google.com/forum/#!topic/meteor-core/1kUoG2mcaRw

Basically, you can do it like this:


<div class="parent">
  {{#if someCondition}}
    {{> blahblah}}


Template.foo.rendered = function () {
  this.find(".parent")._uihooks = {
    insertElement: function (node) {
      if (node.type === "radio") {

This could potentially be more generalized, but you still need to find the parent of the new node.


Great! That’s what I need.

(the only thing I don’t like is preceding underscore - means this feature might be changed/removed)


Yep, that’s correct. It could potentially be removed in the future, but a good number of people are using it so we’ll probably think twice before making a breaking change. If we do, we’ll make sure to warn people and provide a suitable replacement.


@sashko Thank you for your help and prompt response :+1: