views:

143

answers:

2

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?

A: 

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);
}
AnthonyWJones
+1  A: 

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);
seth
Thank you very much. Worked like a charm.
Amy
You are welcome.
seth