node.js socket.io定时器 - 单例模式?

时间:2012-03-27 21:27:32

标签: javascript node.js socket.io

我正在使用node.js和socket.io来显示倒计时器。定时器在node.js上运行,并通过socket.io向客户端发出时间,时间是使用setTimeout。

问题在于,对于每个连接,我实例化一个新的原型类,它正在获取时间并发出定时器,但每个用户的时间应该是相同的。理想情况下,我会使用io.sockets.emit(与使用'socket'回调相反)。然后将时间发送给所有客户端(这是期望的行为)。

现在,这会导致计时器疯狂,因为每个连接的客户端都有一个新对象。

在JavaScript中,单例模式是否可以解决这个问题?

我试图使用它,但似乎没有用:

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
    };

}

我称之为:

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

这仍然会多次创建对象。

任何建议都会很棒!谢谢。

2 个答案:

答案 0 :(得分:1)

Auction.instance = null;

if(!Auction.instance) {

if子句将始终通过,因为它遵循将其设置为null的语句。您希望在函数外部将其设置为null - 而不是每次创建实例时都是如此,因为每次执行new时都会清除单例。

在您的情况下,您也可以从null开始消除整个!undefined === true内容。

答案 1 :(得分:1)

如果您在客户端连接时拨打new Actioninit,那么您将创建多个计时器。您需要在任何连接处理程序之外执行此操作。

编辑:完成此操作后,您还应该遵循@ pimvdb的建议。