2013-08-15 17 views
5

ここにはfiddleがあります。私はmoment.js使用するカウントダウンオブジェクトを作成しようとしているSetInterval()を使用してJavascriptオブジェクトメソッドを呼び出す

(私は日付を使用して上のほうのプラグインを())

var Countdown = function(endDate) { 
    this.endMoment = moment(endDate); 

    this.updateCountdown = function() { 
     var currentMoment, thisDiff; 

     currentMoment = moment(); 
     thisDiff = (this.endMoment).diff(currentMoment, "seconds"); 

     if (thisDiff > 0) 
      console.log(thisDiff); 
     else { 
      clearInterval(this.interval); 
      console.log("over"); 
     } 
    } 

    this.interval = setInterval(this.updateCountdown(), 1000); 
} 

私はそのようにように、カウントダウンのインスタンスを作成します。

var countdown = new Countdown("January 1, 2014 00:00:00"); 

しかし、この機能は1回だけ実行されているようです。何か案は?代わりにsetTimeout()を使用する必要がありますか?

+1

'this.updateCountdown'を' setInte rval'。 – fbynite

+0

オブジェクトを参照していないようです(エラー ''未定義のメソッド 'diff'を呼び出せません):http://jsfiddle.net/zCFr5/2/ – dougmacklin

+0

このようなことをする必要がありますhttp:// jsfiddle .net/zCFr5/3/ – fbynite

答えて

3

あなたは次のようにローカル変数としてごthisコンテキストを保存することができ、次のいずれか

var Countdown = function(endDate) { 
    var self = this; 
    this.endMoment = moment(endDate); 

    this.updateCountdown = function() { 
     var currentMoment, thisDiff; 

     currentMoment = moment(); 
     thisDiff = (self.endMoment).diff(currentMoment, "seconds"); 

     if (thisDiff > 0) 
      console.log(thisDiff); 
     else { 
      clearInterval(self.interval); 
      console.log("over"); 
     } 
    } 

    this.interval = setInterval(this.updateCountdown, 1000); 
} 

それとも、単に直接のようなあなたの変数を使用することができます:私は好む

var Countdown = function(endDate) { 
    var endMoment = moment(endDate); 

    this.updateCountdown = function() { 
     var currentMoment, thisDiff; 

     currentMoment = moment(); 
     thisDiff = (endMoment).diff(currentMoment, "seconds"); 

     if (thisDiff > 0) 
      console.log(thisDiff); 
     else { 
      clearInterval(interval); 
      console.log("over"); 
     } 
    } 

    var interval = setInterval(this.updateCountdown, 1000); 
} 

2番目のアプローチ - fiddle

9

参照を実行すると、その結果は機能しません。 また、この方法でメソッドを呼び出すには、いくつかの「魔法」が必要です。

var me = this; 
this.interval = setInterval(function() { 
    me.updateCountdown(); 
}, 1000); 
+0

'this'への参照を保存する代わりに、' Function.bind'を使うことができます。 http://stackoverflow.com/a/6065221/139010 –

+0

はい、古いブラウザでは動作しません。そしてそれが疑問に暗示しているフレームワークはありません。 – kirilloid

+0

まだ動作していないようですが、ここに更新されたフィドルがあります:http://jsfiddle.net/zCFr5/1/ – dougmacklin

関連する問題