简体   繁体   中英

Event.Trigger Event.Publish f#

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).

It's explained here very well.

In short, think of event.Publish as a way to expose the event, so that clients can subscribe to by calling the Add function. event.Trigger raises the actual event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM