如何在不使用{{#each}}时使模板渲染功能正常工作

时间:2014-04-03 17:27:22

标签: templates meteor each meteor-blaze

所以,我一直试图弄清楚如何在Meteor中使用渲染函数,因为升级到0.8.0。 Blaze会更改渲染函数的行为和now it is only called once

在寻求帮助时,我找到了两个解释如何使用这种新方法获得旧功能的示例。 Meteorpedia,请查看标题为“使用外部脚本(例如jQuery)的新渲染行为”一节。而Avital的github repo显示了两种处理问题的新方法。

然而,这些都不适合我。我的问题是我没有使用{{#each}}块循环遍历内容。我只需要在迭代信息上运行渲染。因此,使用上面的示例,每次将新项添加到数据库时都会调用渲染。但是这对我来说不起作用,因为我只需要在页面渲染后显示信息并运行一些jquery样式内容。

所有这一切都说我发现如果我检查数据是否有内容,渲染的功能对我来说是正常的。如果有人想看看我做了什么,我有repo以下文件。

基本上下面发生的事情是,在{{#each data}}和{{#if data}}块中调用时,“justName”渲染函数中发生的操作会起作用,但如果两者都没有,则发生得太快使用。对于理解这一点的人(我不这样做)这可能是有意义的,但它似乎确实起到了这个作用。

HTML

<template name="infoEach">
{{#each data}}
    <ul>
        <li class="name">{{> justName}}</li>
    </ul>
{{/each}}
</template>

<template name="infoIf">
{{#if data}}
    <ul>
        <li class="name">{{> justName}}</li>
    </ul>
{{/if}}
</template>

<template name="infoNothing">
<ul>
    <li class="name">{{> justName}}</li>
</ul>
</template>

<template name="justName">
    <span class="justName">{{name}}</span>
</template>

JS

// Collection
Items = new Meteor.Collection("items");

// Fixture
if (Items.find().count() === 0) {
    Items.insert({ name: "Matt" });
    Items.insert({ name: "Karen" });
}

// Info Each
Template.infoEach.helpers({
    data: function() { return Items.find(); }
});
Template.infoEach.rendered = function() {
    console.log(this.$(".name").text());
}

// Info If
Template.infoIf.helpers({
    data: function() { return Items.findOne({name: "Matt"}); }
});
Template.infoIf.rendered = function() {
    console.log(this.$(".name").text());
}

// Info Nothing
Template.infoNothing.helpers({
    data: function() { return Items.findOne({name: "Matt"}); }
});

Template.infoNothing.rendered = function() {
    console.log(this.$(".name").text());
}


// Just name
Template.justName.rendered = function() {
    var ran = Random.choice(["blue", "red", "orange"]);
    var txt = this.$(".justName").text();

    this.$(".justName").text(txt + " " + ran);
    this.$(".justName").addClass("added").css("color", ran);

    console.log(this.$(".justName").text());
}

有几点需要注意:

  1. 在此示例中,“infoNothing”模板上的呈现函数在所有其他模板之前调用。

  2. 在Avital的github repo中使用的方法是使用“Items = new Meteor.Collection(”items“,{connection:null});”它确实与“infoNothing”模板一起使用,但是如果我使用更典型的连接,它就会失败。

  3. 希望这将提供对新渲染功能的一些了解。如果我有任何错误或有人有更好(更有经验)的信息,请评论。感谢

0 个答案:

没有答案