PubSub is a very simple Publish-Subscribe module for Xojo. Ported my my LiveCode version of the same: https://github.com/stam66/skPubSub (if anything highlights the elegance of LiveCodeScript compared to the tortuous verbosity often needed in Xojo). A simple way to avoid raising convoluted events and event handlers especially where unrelated objects need to react to the same message. Now changed to delegate based module for type safety and speed. Limitations include not being thread-safe, use at your own risk broadcasting inside a thread.
The module implements a delegate:
Delegate: EventCallback(data As Variant)
All callbacks' signatures now need to have a single variant parameter even if it’s nil.
The module has a private property to store subscriptions: Private mSubscriptions As Dictionary
Dictionary structure: Dictionary[EventName:String] → Dictionary[Target:Object] → EventCallback()
The module includes 6 methods:
Subscribe(eventName As String, callback As EventCallback, target As Object)Subscribe an object to a message that may be broadcastBroadcast(eventName As String, data As Variant = Nil)Broadcast a message to all subscribed objectsUnsubscribe(eventName As String, callback As EventCallback, target As Object)Unsubscribe an object from a specific messaage that may be broadcastUnsubscribeAll(eventName As String, target As Object)Unsubscribe all callbacks for a target from an eventUnsubscribeTarget(target As Object)Remove all subscriptions for a target across all eventsRemoveAllSubscriptions()
// Add a method to your WebPage
Public Sub HandleDataChanged(data As Variant)
MessageBox("Event received: " + data.StringValue)
End Sub
// In Opening event or a button:
PubSub.Subscribe("TestEvent", AddressOf HandleDataChanged, Self)
PubSub.Broadcast("TestEvent", "Hello World!")
// Test unsubscribe
PubSub.Unsubscribe("TestEvent", AddressOf HandleDataChanged, Self)
PubSub.Broadcast("TestEvent", "Should not appear") // Won't trigger
// Or test removing all
PubSub.RemoveAllSubscriptions()