Propagating Events with Rails and Prototype

This weekend, I finally figured out a good method of propagating events on my web page to notify other elements to update themselves. When your working on an AJAX application there is a need to update other sections of a page based on an event. This can be done manually, but I’m dynamically building my page content and the event generator does not know ahead of time who might want to be notified. So, I present my solution below, I’m sure this is old news for the pros, but it took me a while of combing through documentation to figure it out.

First Lets create something to generate an “Event”.

<% form_remote_tag  :update => "my_results_div",
	:url => { :controller => 'posts', :action => 'add_post' },
	:complete => "document.fire('posts:updated')" do -%>
	...
<% end -%>

The important part is the statement document.fire(‘posts:updated’) on the complete. This is a prototype method to fire an event. You must put your event name within a namespace like so I prefixed mine with “posts:”

Now, create a listener for the event.

document.observe('posts:updated',  function() {
	new Ajax.Updater('post_titles', '/posts/titles_list',
	{ method: 'get',
	  evalScripts: true
	});
  });

So, now anywhere in your page you can add the above statement document.observe(‘posts:updated’…. When someone calls document.fire all listeners will be notified, at which time they can update themselves. The above example does an ajax update of the div ‘post_titles’ with the results from my controller method ‘/posts/titles_list’.

I broke my page into lots of little dynamic widgets, and each widget self registers for the events they are interested in. Then I have my main section of the page fire the appropriate events at the right time.

The above code was shown using Rails and Prototype, but you could just use Prototype and your own scripting language.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: