[MacRuby-devel] Added NSNotification support to HotCocoa

Richard Kilmer rich at infoether.com
Fri Sep 19 06:22:31 PDT 2008


I added the ability to easily support notification posting and  
subscribing in HotCocoa:

You can subscribe to notifications with the on_notification method.

on_notification :sent_by => object, :named => "SomeName" do | 
notification|
   #...do something
end

This method is available on the HotCocoa module and on individual  
objects.  When its
used globally you can specify the sent_by object and/or the named  
option.  When its
called on a particular object, the sent_by is that object and you  
don't have to specify
it.

require 'hotcocoa'
include HotCocoa

#here sent_by will be nil...so you will receive all  
NSWindowDidResizeNotification notifications
on_notification :named => 'NSWindowDidResizeNotification' do | 
notification|
   puts "A window resized!"
end

application do
   window :size => [300, 100] do |win|

     #here :sent_by => win
     win.on_notification do |notification|
       puts "Received notification of #{notification.name} on my window"
     end

     tb = toolbar :default => [:show_fonts], :size => :small, :display  
=> :icon_and_label
     win.toolbar = tb
   end
end

You can also pass in :distributed => true and subscribe to the  
distributed notification center.
When you do that the option of :when_suspended can be supplied (which  
defaults to
:coalese) and map as:

     DistributedBehaviors = {
       :drop                 => NSNotificationSuspensionBehaviorDrop,
       :coalesce             =>  
NSNotificationSuspensionBehaviorCoalesce,
       :hold                 => NSNotificationSuspensionBehaviorHold,
       :deliver_immediately  =>  
NSNotificationSuspensionBehaviorDeliverImmediately
     }

You can see the Cocoa docs on what these mean.

The object returned from on_notification is a NotificationListener  
instance that you can
then use to stop receiving notifications by calling  
#stop_notifications on the instance:

     listener = win.on_notification do |notification|
       puts "Received first notification of #{notification.name} on my  
window and now stopping!"
       listener.stop_notifications
     end

To post notifications you can do:

notification :name => "SomeName", :object => some_object, :info =>  
{:key => 'value'}

If you do that it will post immediately, if you don't want it to post  
you can do:

notification ...options..., :post => false

You can also supply :distributed => true and it will post a  
distributed notification.

Best,

Rich


More information about the MacRuby-devel mailing list