Skip to content

Instantly share code, notes, and snippets.

@cesare
Created September 5, 2010 14:53
Show Gist options
  • Save cesare/566070 to your computer and use it in GitHub Desktop.
Save cesare/566070 to your computer and use it in GitHub Desktop.
# -*- mode: ruby; coding: utf-8 -*-
#
# naive imitation #1 of NSNotificationCenter of Cocoa Framework
#
class NotificationCenter
def self.default
@instance ||= NotificationCenter.new
end
def initialize
@queue = Queue.new
@observers = []
start
end
def add_observer(observer, method, name, object = nil)
@observers << { :name => name, :observer => observer, :method => method, :object => object }
end
def remove_observer(observer, name = nil, object = nil)
@observers.reject! do |o|
o[:observer] == observer && (name.nil? || o[:name] == name) && (object.nil? || o[:object] == object)
end
end
def post(name, object = nil)
@queue.push({:name => name, :object => object})
end
private
def start
thread = Thread.start do
loop do
notification = @queue.pop
notify(notification)
end
end
end
def notify(notification)
name = notification[:name]
object = notification[:object]
@observers.each do |observer|
if observer[:name] == name && (object == nil || observer[:object] == object)
observer[:observer].send observer[:method], object
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment