2009-09-04 71 views
1

我正在研究一個包含一些YUI對象的Javascript對象。關鍵是,我的對象需要包含它自己的一組YUI選項卡,以便我可以在同一頁面上顯示我的對象的多個實例,並讓這些選項卡控制它們自己的對象實例。使用YUI和Javascript嵌套對象

我將它設置如下:

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

}); 

這裏的問題。我期望警報(這);在this.showWeek中提醒調度程序的實例。相反,它給我的標籤李。我試着警告this.parent,並給出'undefined'作爲答案。

我應該如何設置它來做我需要做的事情?

回答

1

addListenter方法需要一個範圍的說法。所以你可以改變你的電話以解決你的問題(因爲你使用的是YUI):

tab0.addListener('click', this.showWeek, undefined, this); 
+0

非常感謝。像魅力一樣工作。 – 2009-09-04 22:54:32

+0

不客氣。 – seth 2009-09-04 22:55:39

0

當您將函數附加到對象的事件(本例中爲tab0所持有的對象)時,通常該對象在執行時變爲該函數的this上下文。

調整你這樣的代碼: -

var self = this; 
this.showWeek(){ 
    alert(self); 
}