views:

164

answers:

1

I'm still trying to get my head around the best way to structure event flows. Someone made a lot of sense by telling me that contained objects should be decoupled from their parent containers so they're reusable between containers. Instead of calling their parent's function, they dispatch an event. Sensible!

I recently myself in the awkward-feeling situation of dispatching an event on a contained object, from its parent. It seems more intuitive for an object to be the one dispatching its own events. Maybe I'm bordering on breaking the Law of Demeter?

Example of what I'm doing:
child.dispatchEvent(new ChildEvent(ChildEvent.IM_BEING_A_CHILD));

Am I correct in feeling strange here, or is it a normal thing for one object to dispatch another object's events?

+6  A: 

You are not necessarily breaking any rules here - if dispatchEvent is a public function then you are allowed to call it from anywhere you like.

If you want to keep things cleaner from an encapsulation point of view you could instead expose an explicit function that the parent can call for a particular event to occur - eg:

child.doSomeChildAction();

and on the child class:

public function doSomeChildAction():void
{
   dispatchEvent(new ChildEvent(ChildEvent.IM_BEING_A_CHILD));
}

This way if you need to change the way child sends the event, what kind of event is sent, or what actions occur when the child sends the event it is all encapsulated in the child class, and so will be easier to manage.

Reuben
So, it seems that you're saying it *is* more of an object's own responsibility to dispatch its events...
Pup
Not necessarily - like I said, public functions are public - It's more about code management than responsibility - it is usually easier to manage changes down the line if objects dispatch their own events.
Reuben
was this answer useful to you? Let me know if you need more explanation...
Reuben
From an OO standpoint, it should be an objects own responsiblity to dispatch its own events. The code given here is a great example of how to do it. But he is right, if it is a public method to call, its not technically wrong. There are frameworks that take advantage of this ability.
Ryan Guill
I believe I understand, but I'm less concerned about *technical* correctness and I'd still like reassurance that it *is* more confusing, and less clear, and more unorthodox for one object to be dispatching another object's events.
Pup
When you put it that way, then yes, as Ryan said, from an OO standpoint objects *should* dispatch their own events, otherwise you are breaking encapsulation - having objects dispatching each other's events *can* be more confusing, depending on the context.
Reuben