Displaying loader while meteor collection loads

前端 未结 3 1120
旧巷少年郎
旧巷少年郎 2020-11-29 03:57

I have a template, task_list, that looks like this:

{{#each tasks}}
    {{> task}}
{{/each}}

Template.task_list.tasks

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 04:12

    Meteor 1.0.4 update: Now that template-level subscriptions are available and the preferred pattern to using iron:router or standalone subscriptions,

    There is a complementary function Template.instance().subscriptionsReady() which returns true when all of the subscriptions called with this.subscribe are ready.

    Inside the template's HTML, you can use the built-in helper Template.subscriptionsReady, which is an easy pattern for showing loading indicators in your templates when they depend on data loaded from subscriptions.

    Example:

    Template.notifications.onCreated(function () {
      // Use this.subscribe inside onCreated callback
      this.subscribe("notifications");
    });
    
    

    This is better than having a generic loading template for the whole page, because the loading section is localized to the part of the page that actually has new data.


    Pre-Meteor 1.0.4:

    The idea is to pass an onReady function to Meteor.subscribe:

    Meteor.subscribe('tasks', function onReady() {
      Session.set('tasksLoaded', true);
    });
    

    Then, make your template depend on the tasksLoaded session variable. In the client JavaScript:

    Template.task_list.helpers({
      tasksLoaded: function () {
        return Session.get('tasksLoaded');
      }
    });
    

    In your template: