Ruby Observer Existence Check
-
Is there any way to check to see if an entity already has an observer attached to it?
I am using:
class MyInstanceObserver < Sketchup;;InstanceObserver def onChangeEntity(entity) #puts "onChangeEntity; #{entity}" end end
and then
my_openings = ent.grep(Sketchup;;ComponentInstance).find_all {|oi| oi.definition.name.include?('OPENING') } my_openings.each do |oi| next unless oi.valid? oi.add_observer(MyInstanceObserver.new) end
But would prefer not to blindly attached an observer always. This loop will have been run previously.
-
How about doing it this way.
Outside of any of your methods...@@obs = MyInstanceObserver.new() unless @@obs
That only runs once and its reference can then be used thus:
oi.remove_observer(@@obs) oi.add_observer(@@obs)
Attempting to remove a non-existent observer does NOT raise an error.
So in this way just one instance of the observer is only ever attached to an instance. -
-
You usually set
@@obs = nil
inside a class [outside of any method].
Then within one of that class's methods [likeinitialize()
] you can set it to be a proper reference - but just the once.
In a class it needs to be@@obs = ...
to persist across instances of the class.
A@obs = ...
in a class only exists during that one instance of the class.In my example I set it only if it's not already set [i.e. it is
nil
].You can set
@obs = ...
within a module, outside of any of its methods and that then persists thereafter.Since I didn't have your whole code I guessed...
-
Thanks TIG. Have not gotten very advanced with Classes etc. so just a simple module. Appreciate the explanation.
-
@tig said:
You can set @obs = ... within a module, outside of any of its methods and that then persists thereafter.
This is true because, a module is an instance of class
Module
.@hank said:
Have not gotten very advanced with Classes etc. so just a simple module.
The
Class
class is the direct child class of classModule
. So classes inherit all ofModule
's functionality, and get a little bit of their own (ie, a few extra methods and the ability to have many instance copies of themselves, that can hold their own instance variable values.)
Advertisement