Chapter 2 - method context 2
HTML
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
<div id="lightswitch"></div>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
CSS
#lightswitch {
width: 100px;
height: 100px;
background-color: red;
margin: 5px;
cursor: pointer;
}
JavaScript
// Programming JavaScript Applications
// Chapter 2
// Method context 2
// apply and call can be used for any object, the are impermanent
// if you want to permanently "marry" a function with an object use apply
var lightbulb = {
toggle: function toggle() {
this.isOn = !this.isOn;
return this.isOn;
},
isOn: false
},
// here happens the important bind - without that the addEventlisenter would bind this to the eventObject
//toggle = lightbulb.toggle.bind(lightbulb),
toggle = lightbulb.toggle,
lightswitch = document.getElementById('lightswitch');
//console.log(lightswitch);
lightswitch.addEventListener('click', toggle, false);
QUnit.test("toggle test with bind", function(assert) {
assert.equal(toggle(), true, "turn the lightbulb on");
assert.equal(toggle(), false, "turn the lightbulb off");
});