public
Last active

loading socket.io using require.js

  • Download Gist
main.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// Require.js allows us to configure shortcut alias
require.config({
// The shim config allows us to configure dependencies for
// scripts that do not call define() to register a module
shim: {
'socketio': {
exports: 'io'
},
'underscore': {
exports: '_'
},
'backbone': {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
}
},
paths: {
jquery: 'jquery.min',
underscore: 'lodash.min',
backbone: 'backbone',
socketio: '../socket.io/socket.io',
}
});
 
define([
'jquery',
'backbone',
'socketio',
], function( $, Backbone, io ) {
 
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
 
 
//Ready to write Backbone Models and Socket.io communication protocol in here :)
 
 
});

Thanks this helped me get that working.

This saved me a lot of frustration! Thanks!

my lazyness thanks you :)

The most recent version of socket.io (0.9.16) is AMD compatible, so you don't need to do much at all. For my application the socket.io server is on a different domain, so we can include the path argument to pull the script from the correct location, but if it's on the same domain you could just require \socket.io\socket.io.

    // socket.io serves up the script ready to go. socket.io.js has the following lines:
    // if (typeof define === "function" && define.amd) {
    //   define([], function () { return io; });
    // }

    // All we need to do is tell it the path to our server:
    require.config({
        paths: {
            socketio: 'http://my.cross.domain.server.com/socket.io/socket.io'
        }
    });

    require(['socketio'], function(io) {
        var socket = io.connect('my.cross.domain.server.com');
        console.log('socket connected');
    });

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.