0

This question is somewhat similar to Meteor : wait until all templates are rendered, but I'm asking it again since it seems unanswered in truth, I'll explain why.

Having the following template code

<template name="home">
    <div>
        <ul>
            {{#each this}}
                {{> item}}
            {{/each}}is ready
        </ul>
    </div>
</template>

<template name="item">
    <li><img src="{{amz-picture-url}}"></li>
</template>

I'd like to execute a code once ALL of "item" are rendered. There're many of them and I tried many methods like onRendered, add iron-router's waitOn to home template, jQuery's imagesLoaded function to try wait for the images...

The accepted answer in the previous question uses iron-router to wait for data to be ready, but I do need the sub templates to be rendered besides the data being ready, I need this to call Masonry.

Is there a realiable way of using Mansory in this Meteor usecase or should I change the approach I'm using completely because there's no way for Mansory to be called at the right moment in this context?

Community
  • 1
  • 1
oblitum
  • 11,380
  • 6
  • 54
  • 120

2 Answers2

1

You could add an onload event handler to your <img>s that counts calls. Once it reaches the count of items, your done.

Something like:

<template name="item">
    <li><img src="{{amz-picture-url}}" onload="countImages()"></li>
</template>

Then in js:

var imageCounter = 0;
function countImages() {
    if(++imageCounter == this.length) {
        // Do whatever you need
    }
}
Amit
  • 45,440
  • 9
  • 78
  • 110
  • currently I'm hacking a way similar to this approach using both `onRendered` on the inner template AND checking `imagesLoaded` after the counter reached count for then to call Masonry. UGLY. – oblitum Jun 02 '15 at 23:04
  • Will try yours. It seems less convoluted. – oblitum Jun 02 '15 at 23:05
0

Well you can´t really execute code once all items are loaded because items is infinite for your client in theory. This is why:

Meteor make use of a socket connection to update its minimongo (your local mongodb in the browser) in realtime in the background. So you never know if you really have every item from the server. It still receives updates/deletions or new items.

To fix this issue you could try this

1.) make sure your subscribtion is ready with a callback

2.) fire a function if your subscribtion is ready to count your items in your minimongo

3.) use this total_count and check when its equal your rendered items count.

btw: make sure you really need this action fired when all items are rendered or is there a better and easier solution by divide and conquer your problem in smaller issues (e.g. for every item)

Dude
  • 1,045
  • 2
  • 15
  • 36