diff --git a/lib/risc/position/object_position.rb b/lib/risc/position/object_position.rb index eb27af93..afc7544e 100644 --- a/lib/risc/position/object_position.rb +++ b/lib/risc/position/object_position.rb @@ -6,6 +6,7 @@ module Risc def initialize( object, at) @at = at @object = object + @listeners = [] raise "not int #{self}-#{at}" unless @at.is_a?(Integer) end @@ -32,6 +33,25 @@ module Risc @at = pos true end + + # Register a handler position change event. + # The object calls position_changed on the handler object + # + # obj.position_changed( changed_position ) + # + # @param [Object] object handling position_changed + def register_listener( handler) + @listeners << handler + end + + def unregister_listener(handler) + @listeners.delete handler + end + + # Trigger position change and pass self to position_changed + def trigger() + @listeners.each { |handler| handler.position_changed( self ) } + end end end end diff --git a/lib/util/eventable.rb b/lib/util/eventable.rb index 0291a38c..79af1edc 100644 --- a/lib/util/eventable.rb +++ b/lib/util/eventable.rb @@ -3,7 +3,7 @@ module Util # Events are stored in the `@events` ivar. module Eventable - # Risc a handler for the given event name. + # Register a handler for the given event name. # The event name is the method name called on the handler object # # obj.on(:foo , some_object_that_implements foo( whateverargs) diff --git a/test/risc/position/test_object_position.rb b/test/risc/position/test_object_position.rb index e9a6acb2..d1d0f6d9 100644 --- a/test/risc/position/test_object_position.rb +++ b/test/risc/position/test_object_position.rb @@ -48,5 +48,31 @@ module Risc assert_equal 5 , pos.at end end + class TestPositionEvents < MiniTest::Test + def setup + @position = ObjectPosition.new(self,0) + end + def test_has_register + assert @position.register_listener(self) + end + def test_can_unregister + assert @position.register_listener(self) + assert @position.unregister_listener(self) + end + def test_fires + @position.register_listener(self) + @position.trigger + assert_equal @position , @trigger + end + def test_no_fire_after_unregister + assert @position.register_listener(self) + assert @position.unregister_listener(self) + @position.trigger + assert_nil @trigger + end + def position_changed(pos) + @trigger = pos + end + end end end