我的目標是每當有人按下接受按鈕,它會自動增加導航欄上的通知。如何讓socket.io + ejs + mongoose正常工作?
邏輯
1)一種管理員按接受按鈕
2)用戶導航欄會聽通知事件,並且將增加計數的數目和消息附加到li元素。
下面是IM希望socket.io通知的圖片會更新
但是我沒有看到任何實時更新
下面的代碼
的socket.io客戶端
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
$('form').submit(function(){
var companyName = $("#companyName").val();
var notification = "Accepted by " + companyName;
var user_id = $('#candidate_id').val();
var notificationCount = parseInt($('#notification').html());
noticationCount += 1;
socket.emit('notify', {notification: notification, userId: user_id, count: notificationCount});
});
socket.on('notify', function(msg){
$('#notification').html(msg.count);
$('#addNotification').append($('<li>').text(msg.notification));
});
</script>
HTML(EJS)代碼 - 這是它應該更新的地方。
<li class="dropdown notifications-menu">
<span id='notification' class="label label-warning"><%= user.notifications.length %></span>
</a>
<ul class="dropdown-menu">
<li>
<ul class="menu" id="addNotification">
<% for(var i=0; i < user.notifications.length; i++) { %>
<li><!-- start notification -->
<a href="#">
<i class="fa fa-users text-aqua"></i> <%= user.notifications[i] %>
</a>
</li>
<% } %>
</ul>
</li>
</ul>
</li>
Serverside集團
io.on('connection', function(socket){
socket.on('notify', function(msg){
User.findById({ _id: msg.userId}, function(err, found) {
if (typeof found === 'undefined') {
// Do something but what should I do?s
} else {
found.notifications.push(msg.notification);
found.save(function(err) {
console.log(msg.notification); // Doesnt even console.log the data.
});
}
});
});
});
再次我的目標是
1)有人提交按鈕,它會根據其tag's id
像id="user_id"
發出的所有隱藏的輸入值。
2)socket.on(「通知」) - >將聽取和通過定向html標籤
3)將數據保存到數據庫中的ID進行實時更新。
但是,上面的實現,我不得不刷新它,然後我可以看到結果。 但如果我加入這一行socket.io客戶方代碼
var notificationCount = parseInt($('#notification').html());
noticationCount += 1;
它甚至不會將它保存到數據庫中,還有什麼地方可以實時更新。我
請借給我你的實時知識:)