Execute jQuery code when template updates


#1

Hi,

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>
{{/if}}

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!


#2

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

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

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

And then use the rendered callback:

Template.blahblah.rendered = function () {
  initialize(this.firstNode);
});

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


#3

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?


#4

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:

HTML:

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

JS:

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

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


#5

Great! That’s what I need.

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


#6

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.


#7

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