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

Events & running object methods when they happen

P: 6
Hello all,
I am new to JavaScript (having no programming background at all), trying to learn how to script myself. But I guess this is the barrier I will not get over without help :(
I did a lot of searching and tried everything I possibly could with no real results.
Let's get to the point: I understand, that when an event is fired, the 'this' keyword points to the element that triggered the event, in my case to a button. Now I want to run an object's method when the event happens:
My code:

Expand|Select|Wrap|Line Numbers
  1. function myObj() {};
  2.  
  3. myObj.prototype.myMethod = function() {
  4. alert('It works!');
  5. }
  6.  
  7. myObj.prototype.button = function() {
  8.     var ctrlInput = document.getElementById('button');    
  9.     var ctrlButton = document.createElement('button');
  10.     var ctrlStatus = document.createTextNode('Start');
  11.     ctrlInput.appendChild(ctrlButton);
  12.     ctrlButton.appendChild(ctrlStatus);
  13.  
  14.     ctrlButton.addEventListener('click', function() {
  15.         if(ctrlStatus.nodeValue == 'Start') {
  16.                         // fire myObj.myMethod();    
  17.                 ctrlStatus.nodeValue = 'Stop';
  18.         } else {
  19.                         // fire another method, which does not matter now  
  20.             ctrlStatus.nodeValue = 'Start';
  21.         }
  22.     }, false);
  23. }
  24.  
  25. aa = new myObj();
  26. aa.button();
Could anyone help me out?

jirka
Jul 20 '08 #1
Share this Question
Share on Google+
3 Replies


100+
P: 428
You don't seem to have added the button to the document, and nodeValue is an integer, not the text content of an element.
Jul 21 '08 #2

rnd me
Expert 100+
P: 427
in a prototype method, this refers to the object to the left of the right-most dot.

however, when bound to an event, this means the element that fired the event.

in your object prototype code, use a line like "var that = this", and then you can refer to that.myMethod to hit the object, instead of using this.myMethod, which hits the element.
Jul 21 '08 #3

P: 6
in a prototype method,...
THANK YOU, now it works (I tried that workaround before and it did not, funny).

mrhoo> I did add the button, the HTML is not shown in the example above to make it easier to follow, however I realize it may be confusing.

I guess modyfing the value through nodeValue is okay, (refering to this: http://developer.mozilla.org/en/docs/DOM:element.nodeValue), as it is a text node. At least it works...

Thank you both.
Jul 21 '08 #4

Post your reply

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