作为 Node.js 新手,我正在尝试更改 Smartphone Remote Control with Node.js and Socket.io Nick Anastasov 的示例,因此不需要密码。
在原始源代码中,app.js 文件在输入单词 kittens 后发送 { access : 'granted' }
一个 Web 表单,script.js 启动其主要任务,例如取消网页模糊:
socket.on('access', function(data) {
if (data.access === "granted") { // XXX Tried removing this line
blurredElements.removeClass('blurred');
form.hide();
$(window).on('hashchange', function() {
// ....
});
socket.on('navigate', function(data) {
// ....
});
}
});
我已更改 app.js,使其根本不会发出 access
。
然后我尝试从 script.js 中仅删除行 if (data.access === "granted")
,但这当然不起作用:网页保持模糊状态,因为不再收到 access
事件(既没有 granted
也没有 denied
)。
我的问题是:我应该如何更改上面的代码,以便在建立连接后运行它?
我应该使用 socket.on('connect')
或 socket.on('connection')
还是同样的问题(因为没有字符串 连接
正在发送)?
更新:
按照 Brad 的建议(谢谢!)我已将 script.js 中的字符串从“access”更改为“connection”,但网页仍然模糊 - 这是完整的源代码:
$(function() {
Reveal.initialize({
history: true
});
var socket = io();
var presentation = $('.reveal');
socket.on('connection', function(data){ // XXX changed this
presentation.removeClass('blurred'); // XXX not called
var ignore = false;
$(window).on('hashchange', function(){
if (ignore){
return;
}
var hash = window.location.hash;
socket.emit('slide-changed', {
hash: hash
});
});
socket.on('navigate', function(data){
window.location.hash = data.hash;
ignore = true;
setInterval(function () {
ignore = false;
},100);
});
});
});
这是完整的 app.js 源代码:
var express = require('express'),
app = express();
var port = process.env.PORT || 8080;
var io = require('socket.io').listen(app.listen(port));
app.use(express.static(__dirname + '/public'));
var presentation = io.on('connection', function (socket) {
socket.on('slide-changed', function(data){
presentation.emit('navigate', {
hash: data.hash
});
});
});
最佳答案
是的,您需要io.on('connection')
。每当新客户端连接时都会触发此事件。
关于node.js - 连接建立后如何运行 JavaScript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707493/