Events & running object methods when they happen

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jirkap
    New Member
    • Jul 2008
    • 6

    Events & running object methods when they happen

    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:

    Code:
    function myObj() {};
    
    myObj.prototype.myMethod = function() {
    alert('It works!');
    }
    
    myObj.prototype.button = function() {
    	var ctrlInput = document.getElementById('button');	
    	var ctrlButton = document.createElement('button');
    	var ctrlStatus = document.createTextNode('Start');
    	ctrlInput.appendChild(ctrlButton);
    	ctrlButton.appendChild(ctrlStatus);
    
    	ctrlButton.addEventListener('click', function() {
    		if(ctrlStatus.nodeValue == 'Start') {
                            // fire myObj.myMethod();    
    		        ctrlStatus.nodeValue = 'Stop';
    		} else {
                            // fire another method, which does not matter now  
    			ctrlStatus.nodeValue = 'Start';
    		}
    	}, false);
    }
    
    aa = new myObj();
    aa.button();
    Could anyone help me out?

    jirka
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    You don't seem to have added the button to the document, and nodeValue is an integer, not the text content of an element.

    Comment

    • rnd me
      Recognized Expert Contributor
      • Jun 2007
      • 427

      #3
      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.

      Comment

      • jirkap
        New Member
        • Jul 2008
        • 6

        #4
        Originally posted by rnd me
        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.mozil la.org/en/docs/DOM:element.nod eValue), as it is a text node. At least it works...

        Thank you both.

        Comment

        Working...