How to make object assign its own method to a DOM node?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Andrej Tv
    New Member
    • Mar 2009
    • 2

    #1

    How to make object assign its own method to a DOM node?

    Hi.
    I'm having troubles to come up with a way to assign an object's method to a DOM-node created by the object without hardcoding object's name.
    For example:
    Code:
    function currancySwitcher(){
        this.currancy = ['euro','usd','sek']
    	
    	var a = document.createElement('a');
    	a.title = this.currancy[0]
    	a.href = '#'+this.currancy[0]
    
    	a.onclick = function(){					
    		myObject.setCurrancy(this.title);
    		return false;
    	}
    
    	this.setCurrancy	 = function(currancy){
    	}
    }
    var myObject = new currancySwitcher();
    This code works, but in that way I'm binded to a specific hardcoded variable name and able to create only one working object of that class per page, which is not good at all.
    How can it be done in another way?
    Thanx.
    Last edited by gits; Mar 2 '09, 11:19 AM. Reason: use code tags instead of format ones
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    do you mean something like this?

    Code:
    function currencySwitcher() {
        this.currency = ['euro','usd','sek'];
     
        var a   = document.createElement('a');
        a.title = this.currency[0];
        a.href  = '#'+this.currency[0];
    
        a.innerHTML = 'foo <br/>';
    
        var me = this;
     
        a.onclick = function() {
            me.setCurrency(this.title);
            return false;
        };
     
        this.setCurrency = function(param) {
            alert(param);
        };
    
        document.body.appendChild(a);
    }
    
    for (var j = 0; j < 10; j++) {
        new currencySwitcher();
    }
    kind regards

    Comment

    • Andrej Tv
      New Member
      • Mar 2009
      • 2

      #3
      Yes!

      Dude, that's exactly what I was looking for!
      I didn't know that a variable created inside an object in this way
      var me = this;
      would still refer to that object otside of it.
      Thanx a lot!

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        it is a closure that you use by assigning a function for the onclick ... in that function we store the reference to the variable me that is a reference to the object's this-context :) ... closures are a quite cool feature in JavaScript ;)

        kind regards

        Comment

        Working...