Created
August 28, 2021 03:52
-
-
Save webuilder240/5f1dbee509a90c1bf3b77d3edb1bde6a to your computer and use it in GitHub Desktop.
EventEmitterをRubyで再実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "./emitter.rb" | |
Emitter.once("hello") do |param| | |
puts "Hello World #{param}" | |
end | |
Emitter.emit("hello", "param") | |
Emitter.emit("hello", "param2") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Emitter | |
@handlers = [] | |
def self.on(key, &block) | |
hander = {"#{key}" => {proc: block, once: false}} | |
@handlers.push(hander) | |
end | |
def self.once(key, &block) | |
hander = {"#{key}" => {proc: block, once: true}} | |
@handlers.push(hander) | |
end | |
def self.off(key) | |
@handlers.delete_if { |h| h.has_key?(key) } | |
end | |
def self.emit(key, params = {}) | |
call_handler = @handlers.find{ |h| h.has_key?(key) } | |
if call_handler | |
@handlers.delete_if { |h| h.has_key?(key) } if call_handler[key][:once] | |
call_handler[key][:proc].call(params) | |
else | |
puts "Not Call Key: #{key}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment