Gambas Documentation - /comp/gb/object/attach

# Object.Attach (gb)

Static Sub Attach ( Object As Object, Parent As Object, Name As String )

Attach an object to its parent.

Name is the name used for searching event handlers in the Parent object.

Every event raised by the object will be managed by an event-handler located in its parent.

If the parent is a class, then the the event-handlers will be static methods of the class.

The following code:

    hObject = NEW MyClass
    Object.Attach(hObject, ME, "EventName")

is equivalent to:

    hObject = NEW MyClass AS "EventName"

### Examples

    PUBLIC Process1 AS Process
    ...
    Process1 = SHELL "find /" FOR READ
    Object.Attach(Process1, ME, "Process1")
    ...

    PUBLIC SUB Process1_Read()

       Message.Info("Got output from Process1!")
       ' and then read and do something with the output...

    END

The next example will create 16 picture boxes and each time one of the picture boxes is clicked (MouseUp) then the underlying data bit in iSwtch and the Picture are toggled.

Here is demonstrated how an array of control elements can receive a signal, in this example the signal "MouseUp"

    PUBLIC pbSwtch AS Object[16]

    PUBLIC iSwtch AS Integer ' The status of all 16 data switches

    PUBLIC imgSwtchOff AS Picture ' This Picture shows a switch, when it is switched off
    PUBLIC imgSwtchOn AS Picture ' This Picture shows a switch, when it is switched on

    PUBLIC SUB Form_Show()

    DIM i AS Integer
    DIM pb AS Object

    imgSwtchOff = Picture["imgSwtchOff.png"]
    imgSwtchOn = Picture["imgSwtchOn.png"]

    FOR i = 0 TO 15
      pb = NEW PictureBox(ME) ' create a new PictureBox, return its handle to pb
      pb.X = 20 + 40 * (15 - i)
      pb.Y = 60
      pb.Width = 32
      pb.Height = 32

      pb.Picture = imgSwtchOff
      pb.Name = "pbSwtch"
      pbSwtch[i] = pb
      Object.Attach(pbSwtch[i], ME, "pbSwtch")
    NEXT
    END

    PUBLIC SUB pbSwtch_MouseUp()
    DIM i AS Integer
    DIM togglemask AS Integer

    i = (Mouse.ScreenX - 20) / 40 ' which of the 16 switches was clicked on ?

    IF i >= 0 AND i < 16 THEN
      i = 15 - i
      togglemask = Shl(1, i)
        iSwtch = iSwtch XOR togglemask
      IF iSwtch AND togglemask THEN
        pbSwtch[i].Picture = imgSwtchOn
      ELSE
        pbSwtch[i].Picture = imgSwtchOff
      ENDIF
    ENDIF
    END