SimpleButton3: SimpleButton3.html

<!DOCTYPE html>

<html>
<head>

<title>Comp 86 example SimpleButton3</title>
<!-- Like SimpleButton2.html, but now more object-like, using class syntax -->

<script>

/*
 * ECMAScript class syntax - looks more like a traditional class definition
 */

class Main { //*6 Initialization
    constructor () { //*6
	new MyButton ("Push me"); //*6 
	new RedButton ("Push me also"); //*6 
    }
}

/*
 * MyButton will *have* a captive HTML button, not *be* a button 
 */
class MyButton { //*1 Use Javascript object and class syntax
    constructor (label) { //*1
	// Instantiate our captive button and keep a pointer to it in ivar
	this.button = document.createElement("input"); //*2 HAVE, not BE, a button
	this.button.setAttribute ("type", "button"); //*2
	this.button.setAttribute ("value", label); //*2
	buttonarea.appendChild (this.button); //*2

	this.button.addEventListener ("click", this.mycallback); //*3 Callback as a method 
    }

    // NB "this" in mycallback will actually be the HTML element!
    mycallback () { //*3
	statusmsg.textContent = "Button labeled '" + this.value + "' was pushed "; //*3 
   }
}

/*
 * To show inheritance syntax
 */
class RedButton extends MyButton { //*4 Use Javascript inheritance
    constructor (label) { //*4
	super (label); //*4
	this.button.style.color = "red"; //*5 Override inherited
    }

    mycallback () { //*5
	statusmsg.textContent = "RedButton labeled '" + this.value + "' was pushed "; //*5
    }
}

window.onload = function () { //*6
    new Main () //*6
}

</script> 
</head>

<body>

<div id="buttonarea">
&nbsp;
</div>

<p><b>Status:</b> <span id="statusmsg">(Nothing pushed)</span></p>
</body>
</html>
[download file]