Unobtrusive Ajax with Merb, Datamapper, and jQuery

This article describes how to add ajax to your merb & datamapper application using jquery. It uses an example from my own project investapp to create a ‘more’ link similar to twitter’s.

First, install the agnostic branch of will_paginate. This isn’t available as a public gem yet, but auxesis maintains a working fork of will_paginate agnostic. Add the following to dependencies.rb

Use will_paginate just like you do in rails applications. Here I’m paginating the messages. I’m also providing .js to the @display messages. Rails does this with the respond_to block.

Add the will_paginate helper links to your view.

Now for the jQuery. First and foremost make sure you are including jquery in your view.

Setup the ajax using jquery. There is a decent amount going on here.

Firstly, create a getWithAjax jquery method. Thanks goes to Ryan Bates jQuery episode for this. This basically tells merb to use the index.js.erb file instead of the index.html.erb file.

Secondly, inside the document ready is code that takes the default will_paginate helper html code and hides all the Prev, 1,2,3,4, Next links, replaces, them with the text ‘More’ like on twitter, and makes them ajaxifiable via a class=‘more-entries’ attribute.

Thirdly, the $(“div.pagination a[rel=‘next’]”).not(‘.next_page’).show(); makes sure only the next page link is viewable.

Finally, we just have to tell merb what to do once the link is clicked and goes to index.js.erb.

Our messages/index action just got hit and returned us @messages. The first //append the partials section appends the next batch of 15 messages below the previous 15 messages – just how twitter does.

The next line shows the next ‘next_page’ link so we will be able to click next again.

And the final line, hides the link we just clicked.

The end.

Picture of Scott Motte

delicious facebook rss twitter

Spitfire Sky | github | archives | resume