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
- 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();
jirka