我制作了一个非常随意的评论系统,现在我想添加回复。因此,当有人在其他人的评论上发布回复时,该用户必须通知某人回复了他们的评论。为了做到这一点,当replier单击回复按钮时,向服务器发出AJAX post请求,服务器然后需要获取第一个评论者的id并使用socket.io向他们发送响应文本(socket.io是如果有另一种方式将回复文本发送给另一个模块或表达自己,则不需要使用)。到目前为止,这是我的代码:
module MyModule
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def fields
(@fields || []) + (superlcass.respond_to?(:fields) ? superclass.fields : [])
end
def field(name)
(@fields ||= []) << name.to_sym
end
end
end
答案 0 :(得分:1)
//app.js file
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var routes = require('./routes/routes')(io);
app.use('/', routes);
//router file
var express = require('express');
var router = express.Router();
var _socket = null;
//list of socket users.once they logout delete the socket by
//delete users[_socket.userid];
var users = {};
var returnRouter = function(io) {
io.sockets.on('connection', function (socket) {
//now _Socket is available inside routes
_socket = socket;
});
router.post('/login', function(req, res) {
//authentication logic
User.findOne({'email': req.body.email}, function (err, user) {
//userid must be unique
_socket.userId= user.userId
//set session variable to store id of the user
req.session.userId = user.userId;
//now every user has a socket associated with their id
users[_socket.userId] = _socket;
});
});
router.post('/reply', function (req, res) {
var commenterId = req.body.userId;
User.findOne({'_id': commenterId}, function (err, user) {
// you can get the id of the logged in user that is the creator
//of the original post from req.session.userId
//if you have implemented session store
//the commenter user object is obtained from findOne method
users[req.session.userId].emit('notification', {
notification: user.username+' commented on your post'
}});
});
res.end();
});
return router;
};
module.exports = returnRouter;