I’m trying to write an object relationship that follows an observer pattern where the observer cares about a specific set of events that occur on the subject.
I’m not sure if this is 100% standard, but the way I’ve constructed it, these event objects are defined within the observer, with custom callbacks that will fire when the event occurs. When an event occurs on the subject, it goes through all it’s observers and looks to see who is watching for this event. If it finds observers watching for this event, it triggers the observer event’s callback.
Since I want my observers to have the flexibility to add and remove, on the fly, events that care to watch, I need for the event object to have the ability to delete itself after running it’s callback… say, for instance, if my observer only wants to respond to an event once, then no longer monitor it.
This seems like a good plan, but I know that a JavaScript object can’t have call delete() on itself.
I was just curious is anyone else out there had ran into this and had come up with an effective solution.
My only thought was that I could pass the reference to the parent observer object, to it’s child event, then when the callback happens, I could call a method within the parent… something like removeEvent(this) passing the event itself to this function. The removeEvent function could then splice out the event from it’s array of events. The only complicated problem would be finding the location of this event object in the array. (taking suggestions on this too, thanks!).
Thanks in advance for the help!
I thought I’d have a go at answering your question but I’m not 100% sure how you’ve implemented your observer pattern. Perhaps there’s something useful in my snippet below. I’ve assumed that the observation is done via callback functions and I’ve assumed nothing about the format of that data so I’m using strings.
The crux of my solution is that the callback receives a reference to the Subject (which is usual in the observer pattern). This reference can be used to detach the callback from the Subject.