2013-09-24 50 views
3

我堅持在publishCreate消息廣播,並不知道我做錯了什麼。publishCreate - 郵件未播放

創建了一個簡單的模型稱爲樣本:

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(); 
    } 
}; 

沒有找到的文檔中,如果模型並publishCreate自動所以我加了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()時,我還必須在控制器中做些什麼?

+0

忘了提及,在顯示有問題的視圖我調用'Sample.subscribe(req.socket)控制器的方法;' –

+0

本教程可能是socket.io和帆的概述HTTP有用://irlnathan.github.io/sailscasts/blog/2013/09/15/episode-20-adding-real-time-events-to-models-in-4-lines-of-code/。 – JohnGalt

+0

publishCreate也不適合我。 1)publishDestroy爲我工作,並確保我的代碼工作正常我只是用publishCreate替換publishDestroy,然後沒有任何廣播。 – Triven

回答

2

您是否在控制器的創建操作中顯式聲明瞭publishCreate?

'create': function(req,res,next){ 
    Sample.create(req.params.all(), function sampleCreated(err,sample){ 
    if(err){console.log(err); } 
    Sample.publishCreate({ 
    id:sample.id, 
    device: sample.device, 
    value: sample.value 
    }); 
}); 
}, 

您應該顯式聲明要發佈的數據點。在這裏,我已經設置了ID,設備和價值以明確發佈。藍圖和自動控制器映射是有用的,但它可能有時非常不穩定和不可靠,尤其是缺乏文檔。更好的具體。

2

這裏可能存在的問題是,包含subscribe調用的控制器操作正在響應HTTP請求運行,不是套接字請求。當請求通過HTTP時,req.socket沒有意義;服務器不知道使用了什麼套接字。爲了使subscribe工作,請求必須通過套接字連接進行,例如,使用sails.io.js庫中的socket.get方法。