当前位置: 动力学知识库 > 问答 > 编程问答 >

Nested Objects With YUI and Javascript

问题描述:

I am working on a Javascript object that contains some YUI objects. The key thing is, my object needs to contain it's own set of YUI tabs so that I can display multiple instances of my object on the same page and have the tabs control their own object instance.

I set it up as follows:

var Scheduler = function(divid,startDate,mode){

this.tabView = null;

...

this.init = function(){

this.tabView.appendTo(this.calendar_cell);

this.tabView.addTab( new YAHOO.widget.Tab({

label: 'Day',

content:'<div id="'+ this.calendar_day_div +'" style="width:100%; height:auto;"></div>'

}));

var tab0 = this.tabView.getTab(0);

tab0.addListener('click', this.showWeek);

}

this.showWeek(){

alert(this);

}

});

Here's the problem. I would expect the alert(this); in this.showWeek to alert the instance of scheduler. Instead, it's giving me the tab li. I tried alerting this.parent and am given 'undefined' as an answer.

How should I set this up to do what I need to do?

网友答案:

The addListenter method takes a scope argument. So you can change your call to the following to solve your problem (since you are using YUI):

tab0.addListener('click', this.showWeek, undefined, this);
网友答案:

When you attach a function to an event of an object (in this case the object held by tab0) then its usually that object that becomes the this context of the function when it executes.

Adjust your code like this:-

var self = this;
this.showWeek(){
  alert(self);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: