Scott Scovell on Visual FoxPro

Monday, October 31, 2005

Binding to objects in a collection

When event binding native objects in VFP, one thing I am always conscience of is scope. That is, keeping both my event source and event handler references in scope. If the event source goes out of scope, the event binding is released. If the event handler goes out of scope, the delegate is never called.

So for a long time I avoided event binding to objects I was managing in a collection. I guess it did not click that once I add the object reference to the collection, the object inherits the scope of the collection object. If any event bindings existed on/to the object I was adding to my collection, the bindings would remain intact.

Here is a cute example of this:

Local oThunderBirds As ThunderBirds

* Launch the thunderbirds !

oThunderBirds = NewObject("ThunderBirds")

oThunderBirds.AreGo()

* Uncomment to show event bindings

*!* AEvents(laEvents, oThunderBirds)

*!* Display Memory Like laEvents

Return

* Collection class

Define Class ThunderBirds As Collection

Function Init()

* Add Thunderbirds to collection

This.AddThunderbird("Scott")

This.AddThunderbird("John")

This.AddThunderbird("Virgil")

This.AddThunderbird("Gordon")

This.AddThunderbird("Alan")

EndFunc

Function AddThunderbird(lpcThunderbird As String)

Local oThunderbird As Custom

oThunderbird = NewObject("ThunderBird")

oThunderbird.Son = lpcThunderbird

* Setup event bindings before adding the object to the collection

BindEvent(This, "AreGo", oThunderbird, "OnGoEvent", 1)

This.Add(oThunderbird, lpcThunderbird)

EndFunc

Function AreGo()

Clear

? "Mr Tracy: Thunderbirds are go !"

EndFunc

EndDefine

Define Class ThunderBird As Custom

Son = ""

Function OnGoEvent()

? This.Son + ": FAB dad!"

EndFunc

EndDefine