问题描述
我有以下模板代码
<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>
我想在呈现所有listItem后执行代码。大约有100个。我尝试了以下
And I'd like to execute a code once ALL of the "listItem" are rendered. There are about 100 of them. I tried the following
Template.home.rendered = function() {
// is this called once all of its 'subviews' are rendered?
};
但它不会等到加载所有视图。
But it doesn't wait until all views are loaded.
知道何时加载所有子视图模板的最佳方法是什么?
What's the best way of knowing when all sub-view templates are loaded?
推荐答案
这就是我的方式继续:
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>
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);
};
lib / collections / items.js
Items=new Mongo.Collection("items");
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();
});
server / startup.js
Meteor.startup(function(){
Items.remove({});
if(Items.find().count()===0){
insertItems();
}
});
我们指定只有在出版物准备就绪时才要呈现我们的项目列表,所以时间数据可用,正确数量的 li
元素将显示在列表呈现的回调中。
We specify that we want to render our list of items only when the publication is ready, so by that time data is available and the correct number of li
elements will get displayed in the list rendered callback.
现在同样使用铁:路由器
waitOn
功能:
client / views / home / controller.js
HomeController=RouteController.extend({
template:"home",
waitOn:function(){
return Meteor.subscribe("items");
}
});
client / lib / router.js
Router.configure({
loadingTemplate:"loading"
});
Router.onBeforeAction("loading");
Router.map(function(){
this.route("home",{
path:"/",
controller:"HomeController"
});
});
client / views / loading / loading.html
<template name="loading">
<p>LOADING...</p>
</template>
使用 iron:router
可能更好,因为它优雅地解决了一个常见的模式:我们不再需要itemsReady助手了,只有当waitOn返回的 WaitList
全局就绪时,才会呈现主页模板。
Using iron:router
is probably better because it solves a common pattern elegantly : we don't need the itemsReady helper anymore, the home template will get rendered only when the WaitList
returned by waitOn will be globally ready.
一定不要忘记添加加载模板并设置默认的加载钩子,否则它将无效。
One must not forget to add both a loading template and setup the default "loading" hook otherwise it won't work.
这篇关于Meteor:等到呈现所有模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!