asp.net ajax属性值timestamp未定义

时间:2012-08-31 14:00:08

标签: javascript asp.net asp.net-ajax

我在asp.net ajax中的值赋值和检索有问题。 timestamp的值未定义

代码:

 /// <reference name="MicrosoftAjax.js"/>

 Type.registerNamespace("LabelTimeExtender1");

 LabelTimeExtender1.ClientBehavior1 = function(element) {
 LabelTimeExtender1.ClientBehavior1.initializeBase(this, [element]);
 this._testelement=this.get_element();
 this._timestamp= this.get_element().attributes['TimeStamp'].value;
 alert(_timestamp);

},

 LabelTimeExtender1.ClientBehavior1.prototype = {
initialize: function() {
    LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'initialize');
    setInterval (this.timer,1000);
    alert("after");

},
dispose: function() {        
    //Add custom dispose actions here
    LabelTimeExtender1.ClientBehavior1.callBaseMethod(this, 'dispose');
},
timer: function(){

   alert(this.timestamp);
            var splitdate=this._timestamp.split(/[:]+/);
            alert(splitdate);
            var date= new Date(this._timestamp);
            alert( date.toString());
            var datenow= new Date ();
            alert(datenow.toString());
            this._element.innerText=" ";
            alert(this._element);
              if(date.getUTCFullYear<datenow.getUTCFullYear)
            {
            alert("year");
             var myelement= this.get_element();
             myelement .innerHTML= date.getUTCFullYear.toString();
            }
            if(date.getUTCMonth<datenow.getUTCMonth)
            {
            alert("month");
            this.get_element().innerHTML=date.getUTCMonth.toString();
            }
            if(date.getUTCDay<datenow.getUTCDay)
            {
            this.get_element().innerHTML=date.getUTCDay.toString();
            }
            if(date.getUTCHours <datenow.getUTCHours )
            {
             this.get_element().innerHTML=date.getUTCHours .toString();
            }
            if(date.getUTCMinutes<datenow.getUTCMinutes)
            {
            this.get_element().innerHTML=date.getUTCMinutes.toString();
            }


},
   set_timestamp: function(value)
  {
  this._timestamp=value;
  },

    get_timestamp: function()
   {
   return this._timestamp;
   }



}
 LabelTimeExtender1.ClientBehavior1.registerClass('LabelTimeExtender1.ClientBehavior1',  Sys.UI.Behavior);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

为什么_timestamp的值未定义?

1 个答案:

答案 0 :(得分:0)

我建议将设置this._timestamp的代码移动到您的initialize函数中。

我的另一个建议是在你自己的代码中使用getter和setter来确保封装。因此,警报实际上是alert(this.get_timestamp())。而且,在initialize函数中,您可以调用this.set_timestamp(this.get_element().attributes['TimeStamp'].value)

感谢评论,我发现问题实际上是在setInterval调用中。当您致电window.setInterval(this.timer, 1000);时,调用timer函数时this引用window,而不是您的对象。所以,做这样的事情:

var self = this;
window.setInterval(function () { 
    self.timer(); 
}, 1000);

这将使this内的timer()引用正确的对象。