By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,453 Members | 961 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,453 IT Pros & Developers. It's quick & easy.

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

P: 2
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:
Expand|Select|Wrap|Line Numbers
  1. function currancySwitcher(){
  2.     this.currancy = ['euro','usd','sek']
  3.  
  4.     var a = document.createElement('a');
  5.     a.title = this.currancy[0]
  6.     a.href = '#'+this.currancy[0]
  7.  
  8.     a.onclick = function(){                    
  9.         myObject.setCurrancy(this.title);
  10.         return false;
  11.     }
  12.  
  13.     this.setCurrancy     = function(currancy){
  14.     }
  15. }
  16. var myObject = new currancySwitcher();
  17.  
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.
Mar 2 '09 #1
Share this Question
Share on Google+
3 Replies


gits
Expert Mod 5K+
P: 5,390
do you mean something like this?

Expand|Select|Wrap|Line Numbers
  1. function currencySwitcher() {
  2.     this.currency = ['euro','usd','sek'];
  3.  
  4.     var a   = document.createElement('a');
  5.     a.title = this.currency[0];
  6.     a.href  = '#'+this.currency[0];
  7.  
  8.     a.innerHTML = 'foo <br/>';
  9.  
  10.     var me = this;
  11.  
  12.     a.onclick = function() {
  13.         me.setCurrency(this.title);
  14.         return false;
  15.     };
  16.  
  17.     this.setCurrency = function(param) {
  18.         alert(param);
  19.     };
  20.  
  21.     document.body.appendChild(a);
  22. }
  23.  
  24. for (var j = 0; j < 10; j++) {
  25.     new currencySwitcher();
  26. }
kind regards
Mar 2 '09 #2

P: 2
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!
Mar 2 '09 #3

gits
Expert Mod 5K+
P: 5,390
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
Mar 2 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.