【发布时间】: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}}
【问题讨论】:
-
您需要使用 socket.io 发出事件并处理发出,以便在用户和客户端之间传递数据。查看 socket.io 文档以获取更多信息。
-
一旦我socket.emit,真正推动DOM变化的函数是什么?
-
您可以参考文档。这真的很简单。您还需要使用套接字而不是 http 调用来插入数据。
-
我已经阅读了文档,但没有看到这个具体案例,还有什么更清楚的吗?
标签: javascript node.js express socket.io handlebars.js