SimpleButton3

SimpleButton3.html  [download]

<!DOCTYPE html>

<html>
<head>

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

<script type="text/javascript">

/*
 * New ECMAScript syntax - looks more like a traditional class definition
 * MyButton will *have* a captive HTML button, not *be* a button
 */
class MyButton { //*1 Use Javascript objects and classes
    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
	document.getElementById("buttonarea").appendChild (this.button); //*2

	// Install our button's event handler
	// NB "this" in callback is normally the HTML element,
	// but now our "self" will be in scope when function is called
	var self = this; //*3 Callback as a method
	this.button.onclick = function () { self.callback(); } //*3
    }

    // Put the callback in a separate method
    callback () { //*3
	document.getElementById("statusmsg").innerHTML = //*3
	    "Button labeled '" + this.button.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
    }

    callback () { //*5
	document.getElementById("statusmsg").innerHTML = //*5
	    "RedButton labeled '" + this.button.value + "' was pushed "; //*5
    }
}

window.onload = function () { //*6 Initialization
	new MyButton ("Push me"); //*6
	new RedButton ("Push me also"); //*6
}

</script> 
</head>

<body>

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

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