Meteor:等到呈现所有模板

eri*_*bae 6 javascript meteor

我有以下模板代码

<template name="home">
    <div class="mainBox">
        <ul class="itemList">
            {{#each this}}
                {{> listItem}}
            {{/each}}
        </ul>
    </div>
</template>

<template name="listItem">
    <li class="item">
        {{username}}
    </li>
</template>
Run Code Online (Sandbox Code Playgroud)

而且我想在呈现所有"listItem"后执行代码.大约有100个.我尝试了以下内容

Template.home.rendered = function() {
   // is this called once all of its 'subviews' are rendered?
};
Run Code Online (Sandbox Code Playgroud)

但它不会等到所有视图都加载完毕.

知道何时加载所有子视图模板的最佳方法是什么?

sai*_*unt 3

我就是这样进行的:

client/views/home/home.html

<template name="home">
  {{#if itemsReady}}
    {{> itemsList}}
  {{/if}}
</template>

<template name="itemsList">
  <ul>
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
</template>

<template name="item">
  <li>{{value}}</li>
</template>
Run Code Online (Sandbox Code Playgroud)

client/views/home/home.js

Template.home.helpers({
  itemsReady:function(){
    return Meteor.subscribe("items").ready();
  }
});

Template.itemsList.helpers({
  items:function(){
    return Items.find();
  }
});

Template.itemsList.rendered=function(){
  // will output 100, once
  console.log(this.$("li").length);
};
Run Code Online (Sandbox Code Playgroud)

lib/collections/items.js

Items=new Mongo.Collection("items");
Run Code Online (Sandbox Code Playgroud)

server/collections/items.js

insertItems=function(){
  var range=_.range(100);
  _.each(range,function(index){
    Items.insert({value:"Item "+index});
  });
};

Meteor.publish("items",function(){
  return Items.find();
});
Run Code Online (Sandbox Code Playgroud)

server/startup.js

Meteor.startup(function(){
  Items.remove({});
  if(Items.find().count()===0){
    insertItems();
  }
});
Run Code Online (Sandbox Code Playgroud)

我们指定仅在发布准备就绪时才渲染项目列表,因此到那时数据就可用,并且正确数量的li元素将显示在列表渲染回调中。

现在使用相同的iron:router waitOn功能:

client/views/home/controller.js

HomeController=RouteController.extend({
  template:"home",
  waitOn:function(){
    return Meteor.subscribe("items");
  }
});
Run Code Online (Sandbox Code Playgroud)

client/lib/router.js

Router.configure({
  loadingTemplate:"loading"
});

Router.onBeforeAction("loading");

Router.map(function(){
  this.route("home",{
    path:"/",
    controller:"HomeController"
  });
});
Run Code Online (Sandbox Code Playgroud)

client/views/loading/loading.html

<template name="loading">
  <p>LOADING...</p>
</template>
Run Code Online (Sandbox Code Playgroud)

使用iron:router可能更好,因为它优雅地解决了一个常见模式:我们不再需要 itemsReady 帮助器,只有当WaitListwaitOn 返回的全局就绪时,主模板才会被渲染。

不要忘记添加加载模板并设置默认的“加载”挂钩,否则它将无法工作。