Skip to content
This repository
Browse code

Add Eventable.off method to cancel callbacks

  • Loading branch information...
commit 186b37345ab6ea2669fd08c0e01a7e4936e45a4c 1 parent d3a9a0e
Joe Lind joelind authored
15 README.md
Source Rendered
@@ -666,15 +666,22 @@ idiom it is available as a public API.
666 666
667 667 ```ruby
668 668 > o = Class.new { include EM::Eventable }.new
669   -=> #<#<Class:0x6dc1310>:0x6dc2ec0>
  669 +=> #<#<Class:0xab63f00>:0xab64430>
670 670 > o.on(:november_5_1955) { puts "Ow!" }
671   -=> [#<Proc:0x6dc6300>]
672   -> o.on(:november_5_1955) { puts "Flux capacitor!" }
673   -=> [#<Proc:0x6dc6300>, #<Proc:0x6dc1ba0>]
  671 +=> [#<Proc:0xad9bf00>]
  672 +> flux = proc{ puts "Flux capacitor!" }
  673 +=> #<Proc:0xab630f0>
  674 +> o.on(:november_5_1955, &flux)
  675 +=> [#<Proc:0xad9bf00>, #<Proc:0xab630f0>]
674 676 > o.trigger(:november_5_1955)
675 677 Ow!
676 678 Flux capacitor!
677 679 => [nil, nil]
  680 +> o.off(:november_5_1955, &flux)
  681 +=> #<Proc:0xab630f0>
  682 +> o.trigger(:november_5_1955)
  683 +Ow!
  684 +=> [nil]
678 685 ```
679 686
680 687 # Suggestions?
18 motion/reactor/eventable.rb
@@ -7,18 +7,28 @@ module Eventable
7 7 # and be passed the arguments that are passed to
8 8 # `trigger`.
9 9 def on(event, &blk)
10   - @events ||= Hash.new { |h,k| h[k] = [] }
11   - @events[event].push blk
  10 + events[event].push blk
  11 + end
  12 +
  13 + # When `event` is triggered, do not call the given
  14 + # block any more
  15 + def off(event, &blk)
  16 + events[event].delete_if { |b| b == blk }
  17 + blk
12 18 end
13 19
14 20 # Trigger an event
15 21 def trigger(event, *args)
16   - @events ||= Hash.new { |h,k| h[k] = [] }
17   - @events[event].map do |event|
  22 + events[event].map do |event|
18 23 event.call(*args)
19 24 end
20 25 end
21 26
  27 + private
  28 +
  29 + def events
  30 + @events ||= Hash.new { |h,k| h[k] = [] }
  31 + end
22 32 end
23 33 end
24 34 end
15 spec/motion/reactor/eventable_spec.rb
@@ -15,6 +15,21 @@
15 15 events = @subject.instance_variable_get(:@events)
16 16 events[:foo].member?(proof).should == true
17 17 end
  18 +
  19 + it 'returns the array of blocks for the event' do
  20 + proof = proc { }
  21 + @subject.on(:foo, &proof).should == [proof]
  22 + end
  23 + end
  24 +
  25 + describe '.off' do
  26 + it 'unregisters events' do
  27 + proof = proc { }
  28 + @subject.on(:foo, &proof)
  29 + events = @subject.instance_variable_get(:@events)
  30 + @subject.off(:foo, &proof)
  31 + events[:foo].member?(proof).should == false
  32 + end
18 33 end
19 34
20 35 describe '.trigger' do

0 comments on commit 186b373

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