65. IDs and Event listeners in HaxeUI

2014-11-07

IDs Event listeners in HaxeUI

In the previous tutorial I showed how to use XML layouts to create interfaces using HaxeUI.

The controls we added through XML don't do much on their own, but their functionality can be added as soon as we get actual access to the elements we've created. This is done similarly to HTML - through the use of IDs.

Let's create a new layout which has a VBox container with multiple children, two of which have IDs set.

You can update the existing code from previous tutorial. Update the mainLayout.xml file to look like this:

<?xml version="1.0" encoding="utf-8" ?>

<vbox width="150">

	<divider text="Divider" />

	<button text="Button with a listener" id="myButton" width="100%" />

	<text text="Text field" id="myText" width="100%" />

	<button text="Button" width="100%" />

	<button text="Button" width="100%" />

	<button text="Button" width="100%" />

	<button text="Button" width="100%" />

</vbox>

As you can see, there's a button with an id "myButton" and a text field with an id "myText", which we can use to access these elements. Go to Main.hx and update the bit function that loads and displays the layout.

Toolkit.theme = new GradientTheme();

Toolkit.init();



Toolkit.openFullscreen(function(root:Root) {

	var view:IDisplayObject = Toolkit.processXmlResource("layouts/mainLayout.xml");

	root.addChild(view);

	

	var vbox:VBox = root.findChildAs(VBox);

});

The findChildAs() method takes a class as its argument and finds the first child in the container that has that specific type. This way we resolve the vbox container.

We can then go further and find the required button and text field using their IDs:

var button:Button = vbox.findChild("myButton", Button);

var text:Text = vbox.findChild("myText", Text);

The findChild() method will find the direct child of the container using an ID and a class.

We can avoid the need to resolve the direct container of a child (the VBox in this case) by passing "true" as a third parameter to the findChild() method, which searches for the child recursively.

Toolkit.openFullscreen(function(root:Root) {

	var view:IDisplayObject = Toolkit.processXmlResource("layouts/mainLayout.xml");

	root.addChild(view);

	

	var button:Button = root.findChild("myButton", Button, true);

	var text:Text = root.findChild("myText", Text, true);

});

Event listeners can be added to the elements using the addEventListener() method or using special properties of the object. For example, here are two ways to set a click listener to the button, which will update the text field when handled:

button.onClick = function (e:UIEvent) {

		text.text = "Clicked!";

	}

	

button.addEventListener(UIEvent.CLICK, function (e:UIEvent) {

		text.text = "Clicked!";

	});