Kristoffer K
Kristoffer K

Reputation: 2053

Meteor.js: Execute method after list has been populated

I just started working on a meteorite package which adds groups/headlines to lists.
See demo here.
Source code for demo is here.

Basically, what I want to do is wait for the list to be entirely populated and then call a method which sets the headlines/groups etc. The way I do it now is by calling a handlebars helper after the {{#each}} loop, like this:

<ul>
{{#each listItems }}
  {{> listItem }}
{{/each}}
</ul>

{{ groupList }}

Where the groupList helper executes the code which I want to run efter the loop gets run (the code which sets the headlines).

This feels kind of ugly, and what I think I would prefer is kind of like a callback to the {{#each}} loop which gets called after it's finished iterating (and importantly if the items in the loop change).
Sort of like the rendered() method for templates I guess.
(And I've of course tried the rendered() method already, but it get's executed before the loop is run.)

Is there such a callback? Or some other technique which would be less ugly than the one I currently use with the handlebars helper?

Upvotes: 1

Views: 87

Answers (1)

user3374348
user3374348

Reputation: 4101

Rather than letting Blaze render the list and then using JQuery to add headers, you could do the grouping and headers in the template itself, like this:

<template name="grouped">
  {{#each groups}}
    <h2>{{heading}}</h2>
    {{#each items}}
      {{> item}}
    {{/each}}
  {{/each}}
</template>
Template.grouped.groups = function () {
  return _.chain(ListItems.find().fetch())
          .groupBy("wins")
          .pairs()
          .map(function (pair) {return {heading: pair[0], items: pair[1]};})
          .value();
};

This seems more 'Meteoric' to me - imperative DOM manipulation is generally the wrong approach in Meteor. I'm not sure how the performance compares.

Upvotes: 2

Related Questions