【问题标题】:Display new entry to all users with Socket.io, Express and Handlebars使用 Socket.io、Express 和 Handlebars 向所有用户显示新条目
【发布时间】:2017-06-01 15:21:51
【问题描述】:

当用户向数据库添加条目时,我希望立即将其反映在所有用户打开的页面上。我在 Socket.io 中使用 Express、MongoDB 和 Handlebars。当 User1 提交一个新条目并将其保存到 MongoDB 时,在不同浏览器的同一页面上的 User2 应该会立即在其页面上看到新条目。我已经测试了连接并在添加新用户时进行控制台日志记录。它适用于单个客户端窗口,但不会向所有客户端广播。

在 server.js 中,我正在保存用户:

// CREATE USER
app.post("/", function(req, res) {
  var randomNumbers = [];
  var min = Math.ceil(req.body.min);
  var max = Math.floor(req.body.max);

  function getRandomInt(min, max) {
    for (var i = 0; i < req.body.howMany; i++) {
      randomNumbers.push(Math.floor(Math.random() * (max - min)) + min);
    }
  };

  getRandomInt(min, max);

  // Create a new note and pass the req.body to the entry
  var newEntry = new Entry({
    name: req.body.name,
    min: req.body.min,
    max: req.body.max,
    howMany: req.body.howMany,
    numbers: randomNumbers
  });

  // And save the new note the db
  newEntry.save(function(error, data) {
    // Log any errors
    if (error) {
      console.log(error);
    }
    else {
      // Or send the document to the browser
      res.send(data);
    }
  });    
});

并且还接收到 socket.io 连接

  io.on('connection', function(socket){
    console.log('a user connected');

   socket.on('disconnect', function(){
    console.log('user disconnected');
   });

   socket.on("newuser", function(data) {
    socket.emit("added", data);
   });
});

在 /public/app.js 中进行 AJAX 调用,然后发出数据

    // When that's done
    .done(function(data) {  
      // Log the response
      console.log(data);
      socket.emit("newuser", data);
    });
});

套接字在我的 main.handlebars 文件中启动并监听添加

<script>
    var socket = io();
    socket.on("added", function(data) {
        console.log(data);
    });
</script>

index.handlebars 显示页面

  {{#each entries}}
  <div class="item">
        <span class="name"> {{this.name}} </span> <em> {{min}} : {{max}} </em>

        {{!--Maps over each number--}}
        <ul class="children">
          {{#each numbers}}
          <li> {{this}} </li>
          {{/each}}
        </ul>

       <div class="buttons">
        <button data-id={{this.id}} type="submit" class="delete button">REMOVE</button>
        <!-- Trigger/Open The Modal -->
        <button data-id={{this.id}} class="rename button">RENAME</button>

        <button data-id={{this.id}} class="updateNums button">MIN / MAX</button>
       </div>
  </div>
  {{/each}}

https://github.com/nathanchr/root-tree-app/tree/socket

【问题讨论】:

  • 您需要使用 socket.io 发出事件并处理发出,以便在用户和客户端之间传递数据。查看 socket.io 文档以获取更多信息。
  • 一旦我socket.emit,真正推动DOM变化的函数是什么?
  • 您可以参考文档。这真的很简单。您还需要使用套接字而不是 http 调用来插入数据。
  • 我已经阅读了文档,但没有看到这个具体案例,还有什么更清楚的吗?

标签: javascript node.js express socket.io handlebars.js


【解决方案1】:

流程应该是这样的:

  1. 在数据库中保存条目
  2. 使用客户端需要的数据从服务器发出套接字事件
  3. 所有客户端都应该监听该事件
  4. 在事件中,使用来自服务器的数据来更新 DOM

Handlebars(据我所知)不支持数据绑定,因此您需要使用 JavaScript 更新 DOM。将新条目附加到现有条目列表中。这对于实时更新非常有用,每当用户刷新页面时,他们都会得到一个完全水合的模板。

【讨论】:

  • 感谢您的帮助。对于第 3 步,这只是一个 socket.on(event, function(newEntry) {...append newEntry to the DOM...} )
  • 我尝试在我的 POST 路由中将 socket.emit("new user added", function() { console.log("Success"); }) 添加到 .done 但没有成功。
猜你喜欢
  • 2017-11-26
  • 2023-03-26
  • 2021-07-10
  • 1970-01-01
  • 2014-10-11
  • 2011-11-13
  • 2018-06-20
  • 2016-12-12
  • 2014-10-23
相关资源
最近更新 更多