publish data change to multiple listeners -
10-17-2008
, 06:35 AM
More experienced programmers may laugh that I had to struggle with
this, but I post it so that others in my position might benefit.
My application allows the user to have many forms open. Some of the
forms allow data items to be changed which should be reflected on
other forms. I cannot predict which forms will be open nor how many
of them. I just know that every time data item X is changed on forms
1 or 2, every occurrence of X on forms 5 and 6 should instantly
reflect the change.
Access support for custom Events seemed to presume that the listener
form had to instantiate the changer form, in a one-to-one
relationship. I couldn't assume this, and now have something working
that handles an unpredictable number of changers and an unpredictable
number of listeners.
==============================
There is a class module named Publisher. Its entire code follows:
Public Event ComposerChange()
Public Event CompositionChange()
Public Sub PublishComposerChange()
RaiseEvent ComposerChange
End Sub
Public Sub PublishCompositionChange()
RaiseEvent CompositionChange
End Sub
===============================
There is the following code in another module:
Global objPublisher As Publisher
Public Function EventPublisher() As Publisher
If objPublisher Is Nothing Then
Set objPublisher = New Publisher
End If
Set EventPublisher = objPublisher
End Function
===============================
Each form which changes data has code like the following:
EventPublisher.PublishComposerChange
or
EventPublisher.PublishCompositionChange
===============================
Each form which wants to listen for data changes has code like the
following:
Private WithEvents centralPublisher As Publisher
Private Sub Form_Open(Cancel As Integer)
Set centralPublisher = EventPublisher()
End Sub
Private Sub centralPublisher_ComposerChange()
Me.ComposerList.Requery
End Sub
===============================
Almost surprisingly, there seems no limit to the number of forms which
can refer to the single Publisher object and listen to its events.
They all get notified.
More sophisticated applications would pass some information when the
event is raised. My application doesn't need that; simply knowing
that "something" has changed is enough.
Suggestions in this newsgroup are welcome, but I don't visit here very
often, and e-mails are automatically trashed. No warranty is
expressed or implied. And yes, you probably would have figured it out
quicker than I did.
HTH |