Java Reference
In-Depth Information
var el = evt.getTarget(e);
var status = document.getElementById("status");
status.innerHTML = "The image changed to " + el.src;
if (el.src.indexOf("mexico") > -1) {
evt.removeListener(el, "click", changeImg);
evt.removeListener(el, "click", updateStatus);
}
}
var imgObj = document.getElementById("img0");
evt.addListener(imgObj, "click", changeImg);
evt.addListener(imgObj, "click", updateStatus);
</script>
</body>
</html>
Save the page as
ch10_example15.html
. Load the page into your browser, and you will see it behave
like
ch10_example11.html
. Clicking the image results in it changing to a random picture, and the text
of the
<div/>
element changes to contain the URL of the new picture.
You've seen this code a few times now, so the pertinent changes are highlighted. First, you want to
include your
eve nt‐utility.js
file.
The next change is how you register the event listeners for the image object. Using your event utility's
addListener()
method, you pass it the image object, event name, and the function:
evt.addListener(imgObj, "click", changeImg);
evt.addListener(imgObj, "click", updateStatus);
In the
changeImg()
and
updateStatus()
functions, you change their first lines to retrieve the event
target to use your new
getTarget()
method:
var el = evt.getTarget(e);
Then inside
updateStatus()
, you modify the code inside the
if
statement to use your new
removeListener()
method:
if (el.src.indexOf("mexico") > -1) {
evt.removeListener(el, "click", changeImg);
evt.removeListener(el, "click", updateStatus);
}
There is, however, an issue with this new version: In old‐IE, the event listeners execute in reverse order.
This is a problem, but one you'll fix at the very end of this chapter.
Next, you rewrite Example 12 to use your new
evt
object.