little event mechanism for changed positions

This commit is contained in:
Torsten Ruger 2018-05-31 17:01:23 +03:00
parent 0e155315aa
commit 49849939a1
3 changed files with 47 additions and 1 deletions

View File

@ -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

View File

@ -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)

View File

@ -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