javascript - Meteor : wait until all templates are rendered -
i have following template code
<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>
and i'd execute code once of "listitem" rendered. there 100 of them. tried following
template.home.rendered = function() { // called once of 'subviews' rendered? };
but doesn't wait until views loaded.
what's best way of knowing when sub-view templates loaded?
this how proceed :
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(){ // 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(); } });
we specify want render our list of items when publication ready, time data available , correct number of li
elements displayed in list rendered callback.
now same using iron:router
waiton
feature :
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>
using iron:router
better because solves common pattern elegantly : don't need itemsready helper anymore, home template rendered when waitlist
returned waiton globally ready.
one must not forget add both loading template , setup default "loading" hook otherwise won't work.
Comments
Post a Comment