Voriki
Voriki

Reputation: 1637

How do two objects communicate (w/ example inside)

If two children have the same parent, how does an event firing from one child get handled by the second child.

So the example is:

TrackerContainer is the parent of Tracker and TrackerPanel. TrackerPanel is the parent of PlayButton. Tracker is a timer-like class and has a stop() method. PlayButton has an activate() and deactivate() method.

How does a call to the stop() method from within Tracker call the deactivate() method from within PlayButton(). I thought of having the time keeping track of occurring in the TrackerContainer class, but that doesn't feel right.

EDIT Here it is in code (JavaScript, by the way):

function TrackerContainer
{
   this.display = new Tracker();
   this.panel = new TrackerPanel();
}

function Tracker
{
   this.play = function() { /* yada */ }
   this.stop = function() { /* yada */ }
}

function TrackerPanel
{
   this.playButton = new PlayButton();
}

function PlayButton
{
   this.activate = function() { /* method called when Tracker is playing */ }
   this.deactivate = function() { /* method called when Tracker is stopped */ }
}

Upvotes: 1

Views: 726

Answers (2)

Rob Napier
Rob Napier

Reputation: 299345

You didn't indicate the language, so we'll talk in general terms. This is the Model-View-Controller pattern. Your PlayButton is a view. Your Tracker is the model and the TrackerContainer is the controller (I'm guessing; it might be a view, in which case you should have a separate controller object).

The view's job is to display things. The model's job is keep track of data. The controller coordinates between the two.

For this problem, you probably want an Observer pattern. The controller observes the model and updates the view as needed. One way to implement the Observer pattern is with a delegate or listener. You create an interface called TrackerListener that TrackerContainer conforms to, with methods like trackerDidStart() and trackerDidStop(). Tracker HAS-A TrackerListener and calls the listener methods whenever the state changes. TrackerContainer then updates the button's state.

Upvotes: 1

Dave
Dave

Reputation: 11162

The simplest solution would be to pass the Tracker a instance of the PlayButton. The tracker, in stop() would call playbutton.deactivate(). If it makes you feel more oop-complient, you could make PlayButton implement a Deactivatible interface, which the tracker would work with.

Upvotes: 1

Related Questions