【问题标题】:Meteor dynamic templates from http call and form来自 http 调用和表单的 Meteor 动态模板
【发布时间】:2016-05-16 10:10:47
【问题描述】:

我目前正在恢复从 HTTP CALL 格式化的 JSON。 该函数使用表单模板提供的参数启动,并通过提交事件将参数推送到变量上。

我的函数 getusershttp 能够返回一些我可以通过 console.log(results.content); 看到的结果:

"results" : [
      {
         "name" : {
            "first" : "Billy",
            "last" : "McKornic"
         },
         "id" : "a1c3fd06c71ccc50998baa02074976b4d639e4cf",
         "situation" : "free",
      },
      {
         "name" : {
            "first" : "Dough",
            "last" : "Wallas"
         },
         "id" : "5694c02beaf20d2d4b5747668b82264af8547e33",
         "situation" : "occuped",
      }
   ],
   "status" : "OK"
}

我想将每个结果放在我的文章模板中:

<template name="articles">
    {{#each results}}
        <header>
            <p>{{name.first}} {{name.last}}</p>
            <p>{{id}}</p>
            <p>{{situation}}</p>
        </header>
    {{/each}}
</template>

为了提供每个结果数据,我必须创建什么模板事件和函数? 目前我有:

Template.articles.helpers({
    results : function() {
      return Meteor.call("getusershttp",FormParamX,FormParamY);   
    }
  });

但是我在页面加载时遇到了 java 错误,因为我的表单没有提交并且 FormParamX 和 FormParamY 没有填充。 如何强制我的模板(事件和函数)等待我的表单提交才能开始提供结果?

谢谢!

【问题讨论】:

    标签: java forms templates meteor dynamic


    【解决方案1】:

    将 FormParamX 和 Y 的值设置为reactive variables,然后你可以简单地这样做:

    results() {
        if( Template.instance().FormParamX.get() && Template.instance().FormParamY.get() ) {
            return Meteor.call("getusershttp",FormParamX,FormParamY);   
        }
    }
    

    然后,只要表单参数发生变化,您就会调用 Meteor 方法并获取适当的数据。

    关于反应变量的其他文档是 here,在 TheMeteorChef 上还有一个不错的 walkthrough

    【讨论】:

    • 谢谢斯蒂芬。你认为我只能使用会话变量而不是反应变量吗?如果我理解得很好,FormParamX/Y 从我的表单模板中获取值。我必须使用会话变量定义这些变量,并在我的文章模板上添加您的测试,以确保在返回我的电话之前填充这些变量。
    【解决方案2】:

    在 Stephen 提示之后,我查看了会话变量,它可以工作!

    为了帮助,我根据我的例子提供解决方案。

    首先,我的表单模板事件函数:

    Template.search.events({
      'submit form':function (event){
        event.preventDefault();
        var FormParamX = event.target.FormParamX.value;
        var FormParamY = event.target.FormParamY.value;
    
        Meteor.call("getusershttp",FormParamX,FormParamY,function(error, results) {
          Session.set("MyUsers",results.content);
        });
      }
    });
    

    在这里,我的会话变量 MyUsers 存储我的 HTTP CALL JSON 输出。

    然后,我的文章模板助手:

    Template.articles.helpers({
      results : function() {
        if (Session.get("MyUsers")) {
          console.log(JSON.parse(Session.get("MyUsers")).results);
          return JSON.parse(Session.get("MyUsers")).results;
        };
      }
    });
    

    助手仅在会话变量 MySearch 具有某些值时才提供它的值。 我测试了更改我的表单,并且在每次提交时,帮助程序按预期提供不同的值。

    我的模板文章现在无法提供每个结果,但这是另一个问题。

    更新:为了提供每个结果值,我需要解析我的 JSON 输出。我更新了代码,现在我的模板可以工作了。

    再一次,谢谢斯蒂芬!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      相关资源
      最近更新 更多