I'm kind of new to OOP, so I still have quite some doubts when it comes to how different objects should communicate with each other. I have a concrete case in which I can't figure out which is the best design between the two that came to my mind.
Basically, I'm building a web user-interface (HTML+javascript) in which there are three main players:
- a bunch of Media objects (pics, vids)
- a MediaManager (a container for the
medias, loads new medias when needed, etc), - and a MediaViewer (a fullscreen stage that shows media in full screen, when they're clicked).
Now, clicking on a Media will trigger its view() method which opens the MediaViewer and sets its content to that of the Media that was clicked.
Once the Viewer is open, the user can further navigate through the medias using the keyboard arrowkeys. The next or previous media to show, when an arrowkey is clicked, is decided by the MediaManager: the manager has a .currentlyViewed property with the current media being viewed, plus it has a list of all the medias, so it knows which media comes next.
My doubt is about the best way to keep this .currentlyViewed property updated.
Option1:
Pass a reference of the MediaManager instance to each Media object on instantiation, and in their view() method, do something like
mediaManager.currentlyViewed = media.id
This is what I'm doing at the moment, however it seems wrong to me that the media objects need to know what properties their "parent" have and change that object so directly. Is this maintainable in the long run, when I'll need to add other functionalities?
Option2:
Make Medias "observable" for changes in their view state, i.e. implement a "registerOnViewCallback" method.
Then it's the MediaManager that does something like:
media.registerOnViewCallback(
function( mediaId ) {
mediaViewer.currenctlyViewed = mediaId;
} );
now medias no longer need to know what properties the MediaManager has, they'll blindly execute whatever callback was given to them. However, this code is more indirect and may be more verbose.
Which is the best pattern, what problems arise with the other one, and why?
Thank you.