[RESOLVED] Rendering fails unless template helpers are wrapped in div - why?


#1

Hi all!

In my app, I am displaying a series of objects in a list view:

<template>
        {{#each item}}
             <<stuff>>
        {{/each}}
</template>

For each item, I check whether the object has been favorited by the current user with a template helper. Based on the result of that check, I want to display an “add” or “remove” button, no results are displayed anymore:

<template>
    {{#each item}}
        <<stuff>
        {{#if currentUser}} // only show for logged in users
            <p>
            {{#if isFavorite}} // "is Favorite" is my template helper
                <a class="btn btn-success favorite-active" href="#" role="button">Remove favorite</a>
            {{else}}
                <a class="btn btn-default favorite-inactive" href="#" role="button">Add as favorite</a>
            {{/if}}
            </p>
        {{/if}}
    {{/each}}
 </template>

I get the following error:

TypeError: this.favoritedBy is undefined1 meteor.js:880:11

When researching this issue, I came across a post that recommended changing the markup or the affected elements. So when I then wrap my {{#if currentUser}} block in a <div>, I get a partial success, in that

  • my page template is rendering and
  • the first element in the list is showing.

This first element happens to be the one that has a favoritedBy attribute, which is dynamically created once a user adds an item as a favorite.

The list should be also showing all the other items, though, instead I get the following error:

Exception in queued task: .isFavorite@http://localhost:3000/app/model/quotes.js?0d27c37671123af39f843283d779143d324c74c3:28:7

Can anyone give an explanation why the <div> is required for my page to render at all?

And what is going wrong with the rest of my list of items (error: “Exception in queued task” above)?

TIA
Matt

P.S.: My helper looks like this:

Item.helpers({
    isFavorite: function() {

        // check if favoritedBy property exists
        if (this.favoritedBy != "undefined") {

            // check if user has been registered as having favorited the item
            return this.favoritedBy.indexOf(Meteor.userId()) != -1; 

        } else {
            return false;
        }
    }
});

#2

Found one error in your helper. Try to change your

if (this.favoritedBy != "undefined")

to this

if(this.favoritedBy !== undefined)

and check if the problem has been solved.


#3

I ended up fixing this by changing my helper to:

isFavorite: function() {
    if ("favoritedBy" in this) {
      return this.favoritedBy.indexOf(Meteor.userId()) != -1;
    } else {
      return false;
    }