Smalltalk delegation / storing message selectors
Asked Answered
C

2

5

I am learning Squeak and I was wondering if there is a way to 'store' a message to be sent to an object.

For example I would like to be able to do the following :

Delegator>>performWith: arg
    |target method|
    target := MyObject new.
    method := #myMethod. "Not sure what goes here"
    target sendMessage: method withArgs: arg. "Or how this call would work"

An alternative approach would be to specify both the target and the method in a block. However it is possible to do using the above approach?

Citified answered 10/8, 2013 at 17:48 Comment(0)
W
4

Well, perhaps i misunderstood your question, but you nearly guessed the answer: Send this message to your "target":

perform: aSymbol with: anObject

or:

perform: aSymbol withArguments: anArrayOfArguments

In your example:

target perform: method with: arg

Weathering answered 10/8, 2013 at 20:42 Comment(1)
Ahh I wasn't aware of the perform message. ThanksCitified
A
4

You can also try using an instance of the MessageSend object.

msg := MessageSend receiver: target selector: #myMethod arguments: #(arg1 arg2).
msg value.  "sends the message to it's receiver"

MessageSend can be used as is. Squeak, Pharo, etc. use MessageSend as the base class for MorphicAlarm - which one can use to delay the execution of message until a certain time in the future.

Happy coding!

Alcus answered 11/8, 2013 at 22:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.