[SOLVED] DOM element within helper coming back undefined


#1

I don’t use Blaze much these days, so I’m finding myself a bit stuck here.

I’ve got this in my template (named featuredProds):

{{#each products}}
  {{> productMobile}}
{{/each}}
<div class="filler-icons">
  {{fillerIcons}}
</div>

And then the corresponding helper:

fillerIcons() {
  let prodCount = Products.find().count();

  if (prodCount % 3) {
    Blaze.renderWithData(Template.fillerIcon, {
      icon: 'CU-icon.svg',
      name: 'Contact Us'
    }, Template.instance().$('.filler-icons')[0]);
  } else {
    return '';
  }
}

I get this error in the console:

W20151013-12:30:39.614(-7) (blaze.js:71) Warning: Blaze.render without a parent element is deprecated. You must specify where to insert the rendered content.

But as far as I know, I am passing the parent element as the third argument. I don’t understand how this works.


#2

Are you sure Template.instance().$('.filler-icons')[0] resolves to a valid DOM element?


#3

Shoot, you’re right. It’s returning no matches for some odd reason (Template.instance().$('.filler-icons').length === 0). But it’s definitely there.

<template name="featuredProds">
  <div class="container-fluid">
    {{#unless Template.subscriptionsReady}}
      {{> loading item="Products"}}
    {{else}}
      {{#unless isMobile}}
        <div class="products row{{centerIfShort}}">
          {{#each products}}
            {{> product}}
          {{/each}}
        </div>
      {{else}}
        <div class="products row">
          {{#each products}}
            {{> productMobile}}
          {{/each}}
          <div class="filler-icons">
            {{fillerIcons}}
          </div>
        </div>
      {{/unless}}
    {{/unless}}
  </div>
</template>

PS: The fillerIcons helper is defined within Template.featuredProds.helpers, so the scope should be OK.


#4

You could use $('.filler-icons')[0] instead


#5

That also comes up empty. What the heck?? But if I check $('.filler-icons').length in the Chrome console, it returns 1.

This is why I don’t like Blaze. I always have problems with things not existing when I think they should.


#6

As usual, wrapping the code block in Tracker.afterFlush works. That’s the usual bandaid for these issues.

Side note: now that I’m using Tracker.afterFlush, Template.instance() is null for some odd reason. So I had to just use $('.filler-icons').


#7

Well honestly, you are using a wrong tool. You should be using the
oncreated calllback, mot a helper. A helper is designed to provide context
whereas oncreated os designed to do things like dom manipulation.

So it is not Blaze’s fault :wink:


#8

Fair enough! I’ll see if I can move it to onCreated or onRendered, and see if it works better there.


#9

So are you suggesting using Blaze.renderWithData within onCreated?


#10

oops sorry I meant onrendered!


#11

Ok… I thought that sounded a bit off! :slight_smile: