【问题标题】:Why does my template not reactive?为什么我的模板没有反应?
【发布时间】:2015-05-22 20:51:46
【问题描述】:

如果我先打开http://localhost:3000/,然后点击测试链接,就会显示roles标签。

但是如果我直接在Chrome地址栏打开http://localhost:3000/test(Input这个url回车),roles标签就不会显示出来了。

这是我的代码:

在客户端启动时我订阅了一些东西:

 Meteor.publish("Roles", function(){
   return Roles.find();
 });

 Meteor.startup(function() {
   if(Meteor.isClient) {
     Meteor.subscribe('Roles');
   }
 });

和角色模板:

 Template.roles.helper( {
   allRoles: function() {
     return Roles.find();
   }
 })

html

      <template name="roles">
      <div>
        {{#each allRoles}}
          <label>test label</label>
       {{/each}}
      </div>
    </template>

问题是 roles 模板在 Roles 准备好之前呈现。 所以这些是没有显示的角色标签。

但是根据 Meteor 文档,助手是一种反应式计算,而对集合的数据库查询是反应式数据源。所以在Roles 准备好之后,{{#with allRoles}} 是响应式的并且应该显示出来。

为什么不显示角色?

然后我将代码重写为:

 Meteor.startup(function() {
       if(Meteor.isClient) {
        roles_sub = Meteor.subscribe('Roles');
       }
     });

Template.roles.helper( {
       allRoles: function() {
         console.log(2);
         return Roles.find();
       },
       isReady: function() {
         console.log(1);
         console.log(roles_sub.ready());
         return roles_sub.ready();
       }
     })

html

<template name="roles">
  <div>
    {{#if isReady}}
    {{#each allRoles}}
      <label>test label</label>
    {{/each}}
    {{/if}}
  </div>
</template>

仍然无法显示角色标签。 控制台给了我:

1
false
1
false
1
true
2

这意味着isReady() 是被动的?但是为什么我的角色标签仍然是空白的?

谁能解释一下?

【问题讨论】:

    标签: meteor meteor-blaze meteor-helper


    【解决方案1】:

    使用 Template.subscriptionsReady

    服务器/publish.js

     Meteor.publish("Roles", function(){
       return Roles.find();
     });
    

    client/client.js

    Meteor.startup(function() {
      Meteor.subscribe('Roles');
    });
    
     Template.roles.helpers({ // --> .helper change to .helpers
       allRoles: function() {
         return Roles.find();
       }
     })
    

    client/templates.html

    <template name="roles">
      <div>
        {{# if Template.subscriptionsReady }}
          {{#with allRoles}}
            <label>{{> role }}</label>
          {{/with}}
        {{ else }}
          loading....
        {{/if}}
      </div>
    </template>
    
    <template name="role">
      <div>{{ _id }}</div>
    </template>
    

    当所有订阅都返回 true 的反应函数

    https://github.com/meteor/meteor/blob/9fe2f4b442ec84eac5352b476d014c977c5ae4a2/packages/blaze/template.js#L424

    【讨论】:

    • 如果我直接在Chrome地址栏打开localhost:3000/test(Input这个url回车不行),roles标签不会显示出来。
    • 啊好的 helper({}) --> helpers({}) ??
    猜你喜欢
    • 2013-11-14
    • 1970-01-01
    • 2013-07-10
    • 2021-02-27
    • 2018-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多