Delegate in AX 2012

Today I will demonstrate you that How to use delegate in AX 2012.



In the AOT, you can add a delegate to a class. Do as follows:
  1. In the AOT, create a class named TestDelegateClass.
  2. Right-click the TestDelegateClass node and then click New > Delegate.
  3. Right-click the delegate node, and then click Edit. This starts the X++ Editor window.
  4. In the Editor window, name the delegate reportColorDelegate.
  5. In the Editor window, make the delegate input one parameter of type str.
  6. Save the delegate.

You can add a method to a class, and then you can subscribe the method to a delegate. Do as follows:
  1. Right-click the TestDelegateClass node and then click New > Method.
  2. Right-click the method node, and then click Edit.
  3. In the Editor window, name the method reportColorEH.
  4. In the Editor window, make the modifiers be static public.
  5. Make the input parameters be the same as for the earlier delegate.
Here is an example of what the X++ code should look like.
X++
static public void reportColorEH(str _color)
{
    info(strFmt("%1 is the color value in the event handler.",_color));
}

You can subscribe the reportColorEH method to the reportColorDelegate delegate as an event handler. Do as follows:
  1. Highlight the node for the reportColorEH method.
  2. Use the mouse to drop the reportColorEH node onto the reportColorDelegate delegate node.

You can add a public method that calls the delegate. The X++ code in the method must look similar to the following code example.
X++
public void callTheDelegate()
{
    this.reportColorDelegate("red");
}

You can write and run a job that calls the public method that calls the delegate. Do as follows:
  1. In the AOT, right-click the node AOT > Jobs, and then click New job.
  2. In the code Editor window, enter X++ code that is similar to the following.
X++
static void Job1(Args _args)
{
    TestDelegateClass myTestDelegateClass = new TestDelegateClass();
    myTestDelegateClass.callTheDelegate();
}
  1. Compile the job by pressing the F1 key while focus is in the Editor window.
  2. Run the job by pressing the F5 key.

Comments