首页 > 解决方案 > 如何刷新车把视图中的数据?

问题描述

我正在开发一个项目,其中一部分向用户显示通知。我有一个用于存储通知的对象,以及一个显示通知的表格。通知以适当的格式写入 JSON 文件以供以后使用。

目前的情况是,该对象每 x 秒都会向其推送新通知,但实际表仅在页面重新加载时显示新消息。

我在寻找:

JSON 文件

[
  {
    "Notification": "Limit Exceeded. Event has occurred. Action needed.",
    "Time": "19:54:34",
    "Date": "Sun Oct 28 2018 "
  },
  {
    "Notification": "Limit Exceeded. Event has occurred. Action needed.",
    "Time": "19:54:34",
    "Date": "Sun Oct 28 2018 "
  }
]

JSON 文件开始为空,并记录了通知。通知从这里提取,并存储在一个空的通知对象中。

车把视图。

<h2 class="page-header">Notifications</h2>
<h2>{{log}}</h2>
<p>Your Latest Notifications can be Found Below.</p>

{{#if notifications}}
    <table style="width:100%" border="1">
      <tr>
        <th>Notification:</th>
        <th>Time:</th>
        <th>Date:</th>
      </tr>
        {{#each notifications}}
            <tr>
                <td>{{[Notification]}}</td>
                <td>{{Time}}</td>
                <td>{{Date}}</td>


            </tr>
        {{/each}}
    </table>
{{else}}
    <h3>No Current Notifications</h3>
{{/if}}

<form method="post" action="/test/notify" id="removeuserform">
  <button type="submit" class="btn btn-default">Reload page.</button>
</form>

当然,页面是使用以下行呈现的。

    res.render('home', {notifications: notifications});

解决方案?

我在这里研究了很多方法,也很想看看你的意见。我见过人们使用 webhook,我见过人们初始化一个按钮点击,它重定向到同一页面。我不能使用 window.reload 功能。我见过人们在 EJS 视图中放置标签,但我使用的是 Handlebars。

当我将新项目推送到对象中时,有没有办法简单地刷新此通知对象中的数据?非常感谢您的任何想法。先感谢您。

标签: node.jshandlebars.jsejsexpress-handlebars

解决方案


我认为你需要关心两个部分:

1、通过socket从服务器实时获取数据。在这里,您有 3 个选项:

2、从JavaScript对象同步数据到视图。这称为数据绑定。基本上,您有一个包含通知的 JS 对象。然后将这些数据呈现为 HTML,将它们显示给最终用户。当该 JS 对象更改时,您的 HTML 应该会自动更新。这是一种单向绑定,从 JS 对象到 DOM(模型到视图)。许多 UI 框架或库可以在这里为您提供帮助。您可以选择一个小工具,例如HyperAppAppRunMithrill等。


推荐阅读