EventAggregator
The EventAggregator class allows communication between loosely coupled components in an application. For a general description on how it works check this link.
The design to handle the same functionality in TypeScript is to implement helper classes which behave in an equivalent way. Let's take a small example in C#:
using Microsoft.Practices.Prism.Events;
public class HyperEvent : CompositePresentationEvent<string>
{}
public class MainClass
{
private IEventAggregator eventAggregator;
MainClass()
{
// Normally the EventAggregator is acquired using dependency
// injection, but here we create our own to keep things simple.
eventAgregator = new EventAggregator();
// Now we subscribe to a handler for HyperEvent.
eventAgregator.GetEvent<HyperEvent>().Subscribe(this.HyperEventHandler);
}
public void SendEvent()
{
eventAgregator.GetEvent<HyperEvent>().Publish("WOW!");
}
public void HyperEventHandler(string message)
{
Console.WriteLine(message);
}
}Using helper classes, the code generated from this example would look like this in Typescript:
First notice that GetEvent() method of EventAggregator now takes one parameter, but in C# it takes none. This is because TypeScript types are erased when compiled into JavaScript, so it needs to pass the type (HyperEvent) as parameter to preserve it.
Second, the Subscribe()
Finally, the Publish()
In C#, to unsubscribe a handler, the Unsubscribe() function is used:
On TypeScript, this function is converted as:
The unsubscribe() method must receive the same parameters as the subscribe() method, because internally it compares both the handler and the owner to find exactly which handler must be unsubscribed. This is the reason why lambdas can't be used to unsubscribe handlers. For example:
The previous example will fail when JavaScript tried to unsubscribe the lambda, because we're creating two different lambda objects: one in the subscribe() method and another one in the unsubscribe() method. Internally, when the unsubscribe() method tries to find which handler it should unsubscribe, it won't find the handler because none is equal to the handler that was passed as parameter.
Now, on C# it is possible to subscribe and unsubscribe lambdas, but this require the use of a SubscriptionToken, like this:
This can be converted to TypeScript in a similar way:
In TypeScript, when the code subscribes to a lambda, the framework uses null as the owner, because a lamba function lexically creates a closure which keeps all needed context to execute such lambda. However, because JavaScript "lost" the lambda object (we don't have a reference to it), the code must use the SubscriptionToken that is returned by the subscribe() method when it wants to unsubscribe the lambda. This is the same behavior that C# has.
Last updated
Was this helpful?