Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js socket.io timers - singleton pattern?

node.js socket.io timers - singleton pattern?

Problem

I'm using node.js and socket.io to display countdown timers. The timers are being run on node.js and emitting the times to the client via socket.io, the times are using setTimeout.

The problem is that with each connection, I'm instantiating a new prototype class that is getting the times and emitting the timers, however the times should be the same for every user. Ideally, I would use io.sockets.emit (as oppose to using the 'socket' callback). Then the times would be emitted to all clients (which is the desired behavior).

Right now, this would cause the timers to go nuts, since theres a new object for every client that connects.

In JavaScript, would a singleton pattern be the solution to this?

I've tried to use this, but didn't seem to work:

var Auction = function() {

    Auction.instance = null;

    if(!Auction.instance) {
        Auction.instance = this;
    } else {
        console.log('instance');
        return Auction.instance;
    }

}

Auction.prototype = {

    init: function() {
        //setTimeout is defined here, along with a lot of other stuff
    };

}

I'm calling it doing:

var auction = new Auction;
auction.init();

This still creates the object multiple times.

Any suggestions would be great! Thank you.

Problem courtesy of: dzm

Solution

Auction.instance = null;

if(!Auction.instance) {

This if clause will always pass because it follows the statement setting it to null. You want to set it to null once outside the function - not each time you create an instance because that way you're clearing the singleton each time you do new.

In your case, you can just eliminate the whole null thing since !undefined === true as well.

Solution courtesy of: pimvdb

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js socket.io timers - singleton pattern?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×