题
当我尝试在选择器位于子模板中的模板上使用它时,findall返回任何内容。
这是html:
<template name="products">
{{#each productList}}
{{> product }}
{{/each}}
</template>
<template name="product">
<div class="box">{{name}}</div>
</template>
.
这是JS:
Template.products.helpers({
productList: function() {
var all = Products.find({}).fetch();
return all;
}
});
Template.products.rendered = function(){
var boxes = this.findAll('.box');
console.log(boxes.length);
}
.
框的输出.Length是0.任何想法我如何获得“框”元素?
解决方案 3
这是正确的答案。我已将其添加到我的铁路路由:
action : function () {
if (this.ready()) {
this.render();
}
}
.
找到了 https://stachoverflow.com/a/23576039/130237 在我试图解决一个不同的问题。
其他提示
根据 findall
仅模板内的元素及其子模板可以匹配选择器的部分。
所以它应该为子模板工作。我用固定的一系列产品尝试了它,它致力于看到您刚刚看到对生成的呼叫之间的延迟和所获取的产品。例如,如果你这样做:
Template.products.events({
'click .box': function (e, t) {
var boxes = t.findAll('.box');
console.log(boxes.length);
}
});
.
然后,如果单击其中一个框,则应查看记录到控制台的正确编号。简而言之,我认为测试可能只是无效。如果您使用的是Iron-Router,则可以尝试为产品添加备向 - 这可能会确保他们在渲染呼叫之前到达。
这是在装入所有产品后运行脚本所做的。
我在所有产品中添加了Last_Product属性。
Template.products.helpers({
productList: function() {
var all = Products.find({}).fetch();
var total = all.length;
var ctr = 0;
all.forEach(function(doc){
doc.last_product = false;
ctr++;
if(ctr == total)
{
doc.last_product = true;
}
return doc;
});
return all;
}
});
.
然后而不是“template.products”,我使用“template.product”来检测是否呈现了最后一个产品。当呈现最后一个产品时,运行脚本。
Template.product.rendered = function(){
if(this.data.last_product){
var boxes = $('.pbox');
console.log(boxes.length);
}
}
.
boxes.length现在具有正确的长度。
感谢David的想法!
不隶属于 StackOverflow