Last active
October 10, 2018 11:59
-
-
Save raine/cfa3c5ab44f79833e2edbc76468bd342 to your computer and use it in GitHub Desktop.
Define socket.io once and use it in any view I want?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Setup basic express server | |
var express = require('express'); | |
var app = express(); | |
// Spool up server | |
var server = app.listen(app.get('port'), function() { | |
console.log('App listening on port %d', app.get('port')); | |
}); | |
// Import socket_api | |
var socket_api = require('./socket_api').mount(server); | |
var home = require('./routes/home')(socket_api) | |
app.use('/', home); // mount middleware for site root |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var router = express.Router(); | |
module.exports = function(socket_api) { | |
// INDEX | |
router.get('/', function(request, response, next) { | |
response.render('home'); | |
// I WANT TO BE ABLE TO USE SOCKET.IO HERE AS DEFINED IN SOCKET_API SO I AM NOT IMPORTING IT | |
// CONSTANTLY. IF ALTERATIONS HAVE TO BE MADE TO ACCOMODATE IMPORTING AND DEFINING SOCKET.IO ONCE SURE | |
// BUT CONSTANTLY IMPORTING IT REQUIRES EXPORTING APP.JS AND EXPOSING `SERVER` WHICH ISN'T DRY. | |
// E.G. TO HAVE io.on('connection') ETC RIGHT HERE | |
}); | |
return router | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var socketio = require('socket.io'); | |
module.exports.mount = function(server) { | |
io = socketio.listen(server); | |
io.on('connection', function(socket) { | |
console.log('Connection!'); | |
socket.on('disconnect', function() { | |
console.log('Disconnection!'); | |
}); | |
socket.on('clicked!', function() { | |
console.log("asddsasdaads"); | |
}); | |
}); | |
return io; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, Could you use socket inside the routes? Is there any caveat to it?