Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'this' inside a link generated by a javascript object

Javascript is pretty shaky for me, and I can't seem to find the answer to this. I have some code along the lines of

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

    this.setHeader = function(){
          header.innerHTML = '<a href="#" onclick="this.showScheduler(1);">Show</a>';

    }

   this.showScheduler = function period(){

        ...
   }

};

My problem is, how do I put the onclick into the HTML so that it properly calls the showScheduler function for the appropriate instance of the current scheduler object that I'm working with?

like image 754
Amy Anuszewski Avatar asked Jun 09 '26 12:06

Amy Anuszewski


2 Answers

I wouldn't do whatever it is you're doing the way you're doing it, but with the code the way you have it, I would do this (lots ofdo and doing :) ):

var Scheduler = function(divid, startDate, mode){
    var that = this;

    this.setHeader = function(){
          header.innerHTML = '<a href="#">Show</a>';
          header.firstChild.onclick = function() { that.showScheduler(1); };
    }

   this.showScheduler = function period(){

        ...
   }
};
like image 197
nickytonline Avatar answered Jun 12 '26 03:06

nickytonline


You should use a framework for this type of thing. If you don't use one then you gotta declare each instance of schedular as a global object, and you will need the name of the instance in order to call it from the link. Look at the following link

http://developer.yahoo.com/yui/examples/event/eventsimple.html

They only show a function being applied, but you can also do something like this

YAHOO.util.Event.addListener(myAnchorDom, "click", this.showScheduler,this,true);

Where myAnchorDom is the achor tag dom object. This will have showScheduler function execute within the scope of your scheduler object.

like image 40
Zoidberg Avatar answered Jun 12 '26 01:06

Zoidberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!