SocketIO using RequireJS client application

Standard

In this article, we are going to use RequireJS and SocketIO to create a structure to allow for an interactive single page app. Socket.IO is used to help developers create interactive applications. For example SocketIO could be used to create, a chat system, real-time notifications, or a polling app.

To use RequireJS and SocketIO together I will include all my libraries via CDN’s to minimize the amount of code in my final project.

The main entry point is conveniently labeled “main.js” is the point at which I load all my external libraries. The final function of this file tells requireJS to continue to load my app.js file.

The app.js in this use case is use to load the router, the router is where all the magic happens.

In router.js I define all my libraries that I have included above. I give them names of my choosing “io” and “$”. I will use these in the initialize method to make a connection to the socket. To make this connection work enter you will need to enter your ip or domain of the socket you wish to connect to. The SOCKET variable is assigned below in the html portion of the code. This of course assumes that you have setup your socketIO server on the other end properly.

The final peice to run this application is to have a webpage to display the output. Using the CDN again I load requireJS and the main entry point file (main.js). If you change your SOCKET variable to a running socket server you should see the log message “I am connected” when the page loads.

A complete download of this project is available on github.