Kill subTemplate


I have a parent template which calls a child template. I want to kill the child template by the press of a button.

Parent Template

<template name="tracker">
     <span id="destroyChild" class="btn" title="destroyTable"></span>


Then, I have an event to attempt and destroy the child template

‘click span[id=destroyChild]’(e, template) {
//This works to remove the Parent template

       Blaze.remove('what do I put here?');

I can’t find anything to use as a param to remove the child template. I keep getting Uncaught Error: Expected template rendered with Blaze.render.

I gave the child template an Id and tried calling this with a selector but no luck. Any ideas? Thanks!

As per the documentation Blaze.remove requires the view object, but it only removes elements from the DOM rendered with Blaze.render.

I created a quick test where I call Blaze.remove on a template inserted with {{>child}}. The onDestroyed callback is triggered but it stays visible in the DOM.

When I instead render the child template with Blaze.render it will be removed from the DOM upon calling Blaze.remove.

It would be much easier to handle this with reactivity, IMHO

1 Like

As @jamgold says, it would be better to handle this reactively.

Changing the way you code in Blaze from directively (“when x happens, do y to make it look like z”) to declaratively (“if x, it should look like z”) is hard at first, but when you grasp the principle :bulb:.

Conside a small change to your parent template:

<template name="tracker">
  <span id="destroyChild" class="btn" title="destroyTable"></span>
  {{#if showChild}}     

Along with a reactive variable to control the display of the child:

Template.tracker.onCreated( function() {
  this.childExists = new ReactiveVar(true);

An event handler to change the button state:{
  'click span#destroyChild'(event, templateInst) {

and a reactive helper:

  showChild() {
    return Template.instance().childExists.get();

Then you’ll have all the wiring needed for reactively destroying the child instance. Blaze will re-render that part of the DOM as if the child was never there.

1 Like