Rails: Unobtrusive and i18n Javascript confirm

How many times do you heard you should separate content from behavior? Never? Hmmm don't try to cheat me.. So, why do you still use :confirm option for link_to helper?

Here a little snippet to archive our goal, and as extra bonus, you get it i18n:

   1  <script type="text/javascript">
   2  //<![CDATA[
   3  window._ authenticity_token = "<%= form_authenticity_token %>";
   4  //]]>
   5  </script>
   6  
   7  <%= link_to t(:'delete'), asset_path(@asset),
   8        :title          => t(:'asset.destroy'),
   9        :class          => "delete",
  10        :'data-confirm' => t(:'asset.destroy_confirm') %>



   1  $(document).ready(function(){
   2    $(".delete").bind("click", function() {
   3      if(window.confirm($(this).attr("data-confirm"))) {
   4        $.ajax({
   5          url: $(element).attr("href"),
   6          data: {
   7            _method: "delete",
   8            authenticity_token: window._authenticity_token
   9          },
  10          type: 'post',
  11          dataType: 'script'
  12        });
  13      }
  14      return false;
  15    });
  16  });



Ok, first of all, I'm using jQuery. When the DOM is ready I'm going to bind all the elements with the delete class to the click event. When a user clicks on the link, it will use the HTML5 custom attribute data-confirm as window confirmation content.

advertising

Comments

  1. Jeffrey Chupp's Gravatar

    Posted by Jeffrey Chupp on 2009-06-17 19:21:57 UTC (permalink)

    Cool, this code looks useful.

    FWIW, that first example is almost impossible to read. Might want to rethink the syntax highlighting...

  2. Clemens Kofler's Gravatar

    Posted by Clemens Kofler on 2009-06-17 21:55:13 UTC (permalink)

    Looks neat.

    However, two things to consider:
    a) It doesn't degrade gracefully. If a user has javascript turned off, they will just get to the show page (just like with Rails, of course).
    b) It's a bit hard to cache (unless you're using url-based locale setting with page caching) because once the translation is in the cache, users with other locales might come in.

    However, nice effort!
    - Clemens

  3. Luca Guidi's Gravatar

    Posted by Luca Guidi on 2009-06-18 08:19:54 UTC (permalink)

    Thanks Clemens, i18n is hard to cache per se, even: <%= t(:some_text) %>.
    As you probably know, this is a snippet from Adva, where we have a full javascript application, I'm figuring out how to start from a base solution for Rails, then enhance with this solution or something similar.

Respond to this article