Bubbling events apotomo-1.0

Ok, our very simple widget tree currently consists of three widgets

app/controllers/dashboard_controller.rb (snippet)
 3  has_widgets do |root|
 4    root << widget(:twitter)
 5    root << widget(:trashbin)
 6    root.respond_to_event :tweetDeleted, :with => :redraw, :on => :twitter
 7  end

Now, bin alters the tweets table and triggers an event.

app/widgets/trashbin_widget.rb (snippet)
 8  def trash(evt)
 9    Tweet.find(evt[:id]).delete
10    trigger :tweetDeleted

Event bubbling

The triggered event starts from bin, climbs up and bubbles to root. To grab it we have to attach an observer to either bin or root.

How could the twitter widget catch that event itself?

The answer is: it can’t. We have to put the observer somewhere on the way between the trashbin and root.

The dirty approach

You may simply put the observer into your controller’s has_widgets block, as we did it above. This works fine, however, your controller now knows details about the widgets that should be hidden from it.

What if the event name changes or the triggering state name? The controller shouldn’t know things like that.

You are better off putting observers into the widgets themselves.

A less dirty way

The observer setup can also happen in the after_add hook, not to be confused with After Eight, a delicious mint and chocolate desert, also suitable as snacks for guests.

app/widgets/twitter_widget.rb (snippet)
 1class TwitterWidget < Apotomo::Widget
 2  responds_to_event :submit, :with => :process_tweet
 3  
 4  after_add do
 5    root.respond_to_event :tweetDeleted, :with => :redraw, :on => widget_id
 6  end

This hook is run after the widget is added to its parent. Usually this means when you call me.root you get the root widget. It’s a convenient way to cleanly encapsulate both logic and observers inside your widget.


blog comments powered by Disqus