Sunday, May 22, 2011

HTML in AIR: Part 11

Today we'll learn how to handle Javascript events using Actionscript.

In the previous tutorail we've learned how to create and call JS functions using AS, but we can do more than that, and actually create listeners for Javascript events.

Here is the code for the HTML page we're going to use in this tutorial. This is a simple page that only contains one button, which has an id of "mybutton".

<html>
<body>
<input type="button" id="mybutton" value="Alert">
</body>
</html>

We can add an event listener for it by refering to the object first using getElementById() and then set its event property to a function. An event property is constructed like this: "on" + event name, for example, onclick, onselect, etc.

Example:

import flash.html.HTMLLoader;
import flash.events.Event;
import flash.net.URLRequest;

var myHtml:HTMLLoader = new HTMLLoader();
myHtml.width = 550;
myHtml.height = 400;
myHtml.load(new URLRequest("air_js.html"));
addChild(myHtml);
myHtml.addEventListener(Event.COMPLETE, onload);

function onload(Event):void
{
myHtml.window.document.getElementById("mybutton").onclick = onClickHandler;
}

function onClickHandler(evt:Object):void
{
trace("clicked!");
}

Note, that when we're doing that, we dont have to put () near the function's name in the line where we apply the event listener. We do have to do it though, if the function we're attaching is not a link, but an unnamed inline function:

function onload(Event):void
{
myHtml.window.document.getElementById("mybutton").onclick = function ():void{trace("clicked!");}
}

Also, note that our event is not an object of the Event class, but instead an Object class. It still has properties such as target and currentTarget, but it isn't an Event.

This is not the only way to add event listeners though. We can use the good old addEventListener() to set Javascript listeners from Actionscript.

To do that, we need to write the event in quotes, without the "on" prefix. For example:

function onload(Event):void
{
myHtml.window.document.getElementById("mybutton").addEventListener("click", onClickHandler);
}

And it will have the same results as the example codes above.

Thanks for reading!

Related:

HTML in AIR: Part 1
HTML in AIR: Part 2
HTML in AIR: Part 3
HTML in AIR: Part 4
HTML in AIR: Part 5
HTML in AIR: Part 6
HTML in AIR: Part 7
HTML in AIR: Part 8
HTML in AIR: Part 9
HTML in AIR: Part 10
HTML in AIR: Part 12
HTML in AIR: Part 13
HTML in AIR: Part 14
HTML in AIR: Part 15
HTML in AIR: Part 16
HTML in AIR: Part 17

No comments:

Post a Comment