Reading code about the creation of new events in f# i've encountered the two calls event.Publish and event.Trigger, but i'm not quite sure about their meaning. Could you explain to me what they do?
Keep in consideration what's written in the manual:
event.Publish
Publishes an observation as a first class value.
event.Trigger
Triggers an observation using the given parameters.
Since i'm Italian the term "observation" used in this context doesn't do me any good.
The typical pattern when implementing a new F# type that exposes an event is to create the event value as a local field, trigger the event using event.Trigger
somewhere in the code and expose it to users of your type using trigger.Publish
:
type Counter() =
// Create the `Event` object that represents our event
let event = new Event<_>()
let mutable count = 0
member x.Increment() =
count <- count + 1
if count > 100 then
// Trigger the event when count goes over 100. To keep the sample
// simple, we pass 'count' to the listeners of the event.
event.Trigger(count)
// Expose the event so that the users of our type can register event handlers
[<CLIEvent>]
member x.LimitReached = event.Publish
The CLIEvent
attribute on the published member is optional, but it is good to know about it. It says that the member will be compiled to a .NET event (and C# will see it as event
). If you do not add it, then F# exposes it just as a member of type IEvent
(which is fine for F# use).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With