Meteor 与 Session.set 和 jQuery 在一个调用中组合在一起

Meteor combined with Session.set and jQuery in one call

本文关键字:一个 调用 在一起 组合 Session set jQuery Meteor      更新时间:2023-09-26

我正在尝试在Meteor中获取一些非常基本的东西,当用户单击按钮时,会调用Session.set(),然后显示一个div。问题是,如果我不调用 Session.set(),则行为符合预期,单击按钮时会显示div。但是一旦我包含 Session.set(),我需要单击两次才能实际显示消息。为了确保可以重现该行为,请确保页面是干净的加载,而不是流星刷新!HTML 的代码是:

<head>
  <title>test</title>
</head>
<body>
  {{> home}}
</body>
<template name="home">
  <div>
    <input type="button" id="addButton" value="add">
  </div>
  {{> popup}}
</template>
<template name="popup">
  {{#with messageHelper}}
  <div id="messageDiv" style="display: none">
    message is {{message}}
  </div>
{{/with}}
</template>

这是让它打勾的Javascript。

Template.home.events({
  'click #addButton': function(){
    // **** if this line is commented out, it will work
    Session.set("messageHelper", {message: 'HERE'});
    // ****
    $('#messageDiv').show();
  }
});
Template.popup.helpers({
  messageHelper: function(){
    return Session.get("messageHelper");
  }
});

我认为更改后的会话变量会以原始状态重新渲染您的模板,该状态设置 style="display: none"。 这里讨论这个问题。 解决方案是重新组织模板,以便反应性不在切换显示的模板中。

更简单的解决方案可能是在出现消息时使用车把 #if 助手来显示您的模板:

<template name="popup">
   {{#with messageHelper}}
     {{#if message}}
       <div id="messageDiv">
         message is {{message}}
       </div>
     {{/if}}
   {{/with}}
</template>

那么在事件处理程序中不需要 .show()。