使用socket.io更新express实时视图

Update view of express real time using socket.io

本文关键字:实时 视图 express 更新 socket io 使用      更新时间:2023-09-26

我使用handlebar作为我的express应用程序的视图引擎。但是如何从socket.io中附加新的数据呢??

router.get('/', function(req, res) {
  io.on('connection', function(client) { 
            client.on('order', function(data) {
                console.log(data); //real time data from mobile app
                //what to do here?
            });
        });
    Orders.getOrdersByUserId(req.user.id, function(err,data){
      res.render('orders/index',{orders:data});
    })
});

似乎索引句柄文件被呈现给客户端,然后异步地,socket.io可以向客户端发送新信息(在您的情况下,会收到新订单)。这些新信息必须通过JavaScript添加到DOM中。使用把手进行的初始视图渲染已经发生。

这是一个关于如何工作的琐碎例子。。。

/server.js

var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
app.engine('handlebars', exphbs({
  defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
app.get('/', function(req, res) {
  res.render('test', {testItems: [1,2,3]});
});
app.listen(3000, function() {
  console.log('listening on 3000');
});

/视图/布局/main.handlebars

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Example App</title>
</head>
<body>
    {{{body}}}
</body>
</html>

/views/test.handlebars

<ul class="test-items">
  {{#each testItems}}
    <li>{{this}}</li>
  {{/each}}
</ul>
<!-- TODO: obviously bring in jQuery the correct way -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<!-- TODO: put custom javascript in individual files instead of inline. Also wire up Socket.IO on the server and the client... just using a mocked out message handler for a simple explanation -->
<script>
  // Mock socket message handler... this would be socket.io on the client side subscribing to a socket.io topic on the server
  setTimeout(function() {
    var inboundDummyData = 9001;
    $('.test-items').append('<li>' + inboundDummyData +'</li>');
  }, 3000);
</script>

结果:页面加载时将显示1、2、3的列表。3秒钟后,我们模拟的Socket.io消息处理程序将收到一条消息,并将9001添加到该列表中。

希望这能让你开始如果我发现Express Handlebars支持实时更新数据,我会更新我的答案,但它似乎只会进行初始视图渲染,仅此而已。

更新:做了一些研究。。。Express车把非常适合初始视图,但之后不支持绑定。如果你想要基于服务器的数据绑定/"实时更新",你应该研究"同构JavaScript"(这里的好文章:https://blog.risingstack.com/from-angularjs-to-react-the-isomorphic-way/)目前在这个领域有一些成熟的框架/库。当然,您也可以使用Angular.js、React.js或Knockout.js等框架,只需前端即可实现数据绑定。这两种技术都适用于Socket.IO,您应该能够通过一些研究找到对Handlebars的支持。