开发者

How to use javascript class from within document ready

I have this countdown script wrapped as an object located in a separate file

Then when I want to setup a counter, the timeout function in the countdown class can not find the object again that I have setup within the document ready.

I sort of get that everything that is setup in the document ready is convined to that scope, however it is possible to call functions within other document ready´s.

Does anyone has a solution on how I could setup multiple counters slash objects. Or do those basic javascript classes have to become plugins

This is the class

  function countdown(obj)
{
    this.obj        = obj;
    this.Div        = "clock";
    this.BackColor      = "white";
    this.ForeColor      = "black";
    this.TargetDate     = "12/31/2020 5:00 AM";
    this.DisplayFormat  = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
    this.CountActive   开发者_JAVA技巧 = true;

    this.DisplayStr;

    this.Calcage        = cd_Calcage;
    this.CountBack      = cd_CountBack;
    this.Setup      = cd_Setup;
}

function cd_Calcage(secs, num1, num2)
{
  s = ((Math.floor(secs/num1))%num2).toString();
  if (s.length < 2) s = "0" + s;
  return (s);
}
function cd_CountBack(secs)
{
  this.DisplayStr = this.DisplayFormat.replace(/%%D%%/g,    this.Calcage(secs,86400,100000));
  this.DisplayStr = this.DisplayStr.replace(/%%H%%/g,       this.Calcage(secs,3600,24));
  this.DisplayStr = this.DisplayStr.replace(/%%M%%/g,       this.Calcage(secs,60,60));
  this.DisplayStr = this.DisplayStr.replace(/%%S%%/g,       this.Calcage(secs,1,60));

  //document.getElementById(this.Div).innerHTML = this.DisplayStr;

  $('#'+this.Div).text(this.DisplayStr);
  $('#tel').text(parseInt( $('#tel').text() )+1);


  if (this.CountActive) setTimeout(this.obj +".CountBack(" + (secs-1) + ")", 990);
}
function cd_Setup()
{
    var dthen   = new Date(this.TargetDate);
    var dnow    = new Date();
    ddiff       = new Date(dthen-dnow);
    gsecs       = Math.floor(ddiff.valueOf()/1000);
    this.CountBack(gsecs);
}

and setting it up

$(document).ready(function() { 
  var cd1 = new countdown('cd1');
  cd1.Div = "clk";
 cd1.TargetDate = "08/15/2010 8:00 PM";
  cd1.DisplayFormat = "%%D%% days, %%H%% hours, %%M%% minutes, %%S%% seconds until event   AAA happens"; 
 cd1.Setup(); 

firebug says it errors out with the timeout function

thanks, Richard


cd1 is defined in the local scope. setTimeout will run the function passed as parameter 1 in the window [global] scope, and in your case, window.cd1 is undefined.

The solution for your problem would to make cd1 a global variable. [Remove the "var" in your declaration of cd1]


Off topic: I recommend you look into using anonymous functions, as they can make your code much more pretty/legible at times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜