I always struggle with sending messages between objects. Consider the hierarchy of objects of a quiz:
- Quiz
- QuestionList
- Question
- AnswerList
- Answer
- AnswerList
- Question
- QuestionList
So:
a Quiz has a QuestionList
a QuestionList has multiple Questions
a Question has an AnswerList
a AnswerList has multiple Answers
When an Answer gets clicked (we’re talking Flash AS3 here):
Answer notifies AnswerList.
AnswerList notifies Question.
Question notifies QuestionList.
QuestionList notifies Quiz.
In other words, the message bubbles up. This is possible since I pass each ‘parent’ object through the constructor of it’s ‘child’. But I think I read somewhere that objects shouldn’t be aware of it’s parent. Should I take another approach?
Thanks.
Yes, you shouldn’t give the child objects links to their parent. I guess you the situation you explained above is a display hierarchy. In that case, you could do it much better using the event system. You can create custom events that are dispatched, when things happen and the parent would add listeners to events to take care of those.
A possible event scenario for your structure would for example be the following: