Reputation: 23534
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.
Upvotes: 0
Views: 2075
Reputation: 185852
If you call new Action
and init
when a client connects, then you will create multiple timers. You need to do this once outside any connection handlers.
EDIT: Once you've done this, you should also follow @pimvdb's advice.
Upvotes: 1
Reputation: 154818
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.
Upvotes: 1