Skip to content
Browse files

Add Eventable.off method to cancel callbacks

  • Loading branch information...
1 parent d3a9a0e commit 186b37345ab6ea2669fd08c0e01a7e4936e45a4c @joelind joelind committed Apr 4, 2013
Showing with 40 additions and 8 deletions.
  1. +11 −4 README.md
  2. +14 −4 motion/reactor/eventable.rb
  3. +15 −0 spec/motion/reactor/eventable_spec.rb
View
15 README.md
@@ -666,15 +666,22 @@ idiom it is available as a public API.
```ruby
> o = Class.new { include EM::Eventable }.new
-=> #<#<Class:0x6dc1310>:0x6dc2ec0>
+=> #<#<Class:0xab63f00>:0xab64430>
> o.on(:november_5_1955) { puts "Ow!" }
-=> [#<Proc:0x6dc6300>]
-> o.on(:november_5_1955) { puts "Flux capacitor!" }
-=> [#<Proc:0x6dc6300>, #<Proc:0x6dc1ba0>]
+=> [#<Proc:0xad9bf00>]
+> flux = proc{ puts "Flux capacitor!" }
+=> #<Proc:0xab630f0>
+> o.on(:november_5_1955, &flux)
+=> [#<Proc:0xad9bf00>, #<Proc:0xab630f0>]
> o.trigger(:november_5_1955)
Ow!
Flux capacitor!
=> [nil, nil]
+> o.off(:november_5_1955, &flux)
+=> #<Proc:0xab630f0>
+> o.trigger(:november_5_1955)
+Ow!
+=> [nil]
```
# Suggestions?
View
18 motion/reactor/eventable.rb
@@ -7,18 +7,28 @@ module Eventable
# and be passed the arguments that are passed to
# `trigger`.
def on(event, &blk)
- @events ||= Hash.new { |h,k| h[k] = [] }
- @events[event].push blk
+ events[event].push blk
+ end
+
+ # When `event` is triggered, do not call the given
+ # block any more
+ def off(event, &blk)
+ events[event].delete_if { |b| b == blk }
+ blk
end
# Trigger an event
def trigger(event, *args)
- @events ||= Hash.new { |h,k| h[k] = [] }
- @events[event].map do |event|
+ events[event].map do |event|
event.call(*args)
end
end
+ private
+
+ def events
+ @events ||= Hash.new { |h,k| h[k] = [] }
+ end
end
end
end
View
15 spec/motion/reactor/eventable_spec.rb
@@ -15,6 +15,21 @@
events = @subject.instance_variable_get(:@events)
events[:foo].member?(proof).should == true
end
+
+ it 'returns the array of blocks for the event' do
+ proof = proc { }
+ @subject.on(:foo, &proof).should == [proof]
+ end
+ end
+
+ describe '.off' do
+ it 'unregisters events' do
+ proof = proc { }
+ @subject.on(:foo, &proof)
+ events = @subject.instance_variable_get(:@events)
+ @subject.off(:foo, &proof)
+ events[:foo].member?(proof).should == false
+ end
end
describe '.trigger' do

0 comments on commit 186b373

Please sign in to comment.
Something went wrong with that request. Please try again.