7.2 – Binding methods to element events at runtime

At section 7.1 we showed how it’s easy to add elements at runtime by code. But how can you add functionality to these elements? It’s also quite easy.

Create a scene with a panel with variableName “panel1″ and a button with variableName “button1″.

Change panel1′s layout to vertical.

There are two main ways of binding a method to an event of an element.


1)

Add an event method manually to iGUICode. Pay attention to signature of this method. A method with name runtimeButton_Click means, this method will be called when the click event of a button with variableName “runtimeButton” is triggered. There aren’t any elements with variableName “runtimeButton” exist yet, but we’ll create a button at runtime and assign “runtimeButton” to its variableName :

//Added manually
public void runtimeButton_Click(iGUIButton caller){
    iGUIRoot.alert("Debug", caller.variableName);
}

public void button1_Click(iGUIButton caller){
    iGUIButton myButton = panel1.addElement<iGUIButton>();
    myButton.setVariableName("runtimeButton");
}
//Added manually
function runtimeButton_Click(caller : iGUIButton){
    iGUIRoot.alert("Debug", caller.variableName);
}

function button1_Click(caller : iGUIButton){
    var myButton = panel1.addElement("iGUIButton");
    myButton.setVariableName("runtimeButton");
}



2)

Add a method manually to iGUICode with signature void methodName(iGUIElement caller). You can assign all methods with that signature to any event easily by callbacks :

//Added manually
public void myMethod(iGUIElement caller){
    iGUIRoot.alert("Debug", caller.variableName);
}

public void button1_Click(iGUIButton caller){
    iGUIButton myButton = panel1.addElement<iGUIButton>();
    myButton.clickCallback += myMethod;
}
//Added manually
function myMethod(caller : iGUIElement){
    iGUIRoot.alert("Debug", caller.variableName);
}

function button1_Click(caller : iGUIButton){
    var myButton = panel1.addElement("iGUIButton") as iGUIButton;
    myButton.clickCallback = System.Delegate.Combine(myButton.clickCallback, myMethod as iGUIEventCallback);
}


To handle more than one element with the same method, you can make use of userData field of all elements to attach any custom data.