我坚持使用 publishCreate 消息广播,不知道我做错了什么。
创建了一个名为 Sample 的简单模型:
module.exports = {
attributes: {
device: 'string',
value: 'float'
},
afterCreate: function(sample, next) {
console.log("afterCreate called");
Sample.publishCreate({value: sample.value});
console.log("publishCreate sent");
next();
}
};
如果模型自动发布创建,则在文档中没有找到,所以我添加了 afterCreate。
然后我创建了以下视图:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/styles/iphone.css">
<!-- Bring in the socket.io client -->
<script type="text/javascript" src="/js/socket.io.js"></script>
<!-- then beef it up with some convenience logic for talking to Sails.js -->
<script type="text/javascript" src="/js/sails.io.js"></script>
<!-- listen on socket.io for incoming messages -->
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript">
socket.on('message', function(msg){
alert('message received');
});
</script>
</head>
<body>
<div class="block" style="height: 320px;">
<div class="centered">
<h1><%= temp %>°</h1>
</div>
</div>
</body>
</html>
理论上现在如果我在浏览器中调用视图,然后在另一个浏览器选项卡中调用
http://localhost:1337/sample/create?device=AA&value=10.0
在上面的视图中,客户端应该会收到一条消息,但没有任何反应。
我从消息中知道套接字已连接,并且在创建新示例时调用了 publishCreate。
可能是什么原因?调用 res.view() 时我是否还必须在控制器中执行某些操作?