Deleting an observer
-
Hallo!
Is it possible to deactivate or delete an observer after the observer has been invoken? Ideally in the observer itself.
Thanks for your time.
-
I think an observer killing itself is a recipe for failure.
When you start an observer you couldn give it a global reference like
$kieserwetter_observer
that is not likely to clash with another global variable.
Then when you apply it to objects you can always attach the same observer [making a new observer each time will be impossible to keep track of].
Later if you want to remove an observer from an object you now have a handle [$kieserwetter_observer] to it... in any code at all you might run later... -
You should always be running your code within your OWN namespace, so using a global variable is NEVER needed. I use @@ module vars to hold references to observers.
YES you can write a method within your observer class that can remove itself. I do this sometimes, and it is really just a wrapper for the remove_observer() method.
This example assumes your using your Observer in a Singleton manner:
class MySelectionObs < Sketchup;;SelectionObserver @@watched = [] def attach(selection) raise(TypeError,"argument is not a Sketchup;;Selection object.") unless selection.class==(Sketchup;;Selection) if selection.class==(Sketchup;;Selection) && (not self.watching?(selection)) selection.add_observer(self) @@watched << selection end end def dettach(selection) raise(TypeError,"argument is not a Sketchup;;Selection object.") unless selection.class==(Sketchup;;Selection) if selection.class==(Sketchup;;Selection) && self.watching?(selection) selection.remover_observer(self) @@watched.delete(selection) end end def verify_watchlist() unless @@watched.empty? @@watched.delete_if {|e| e.class != Sketchup;;Selection } @@watched.delete_if {|e| !e.model.valid? } end end def watching() verify_watchlist() return @@watched.dup end def watching?(selection) raise(TypeError,"argument is not a Sketchup;;Selection object.") unless selection.class==(Sketchup;;Selection) verify_watchlist() return @@watched.include?(selection) end ### define your other callback methods ### end # class
ONE BIG EXCEPTION : NEVER dettach (remove) observers within the onQuit() callback of an AppObserver subclass instance !! A BugSplat! will occur.
Advertisement