Search code examples
jqueryruby-on-rails-3prototypejsujs

Railcasts 103 - Conversion from Prototype to Jquery, Help Needed


I'm a dunce when it comes to this and I'm totally stuck. Following railscast 103, I'm trying to implement an announcement system with rails 3.2.3

The tutorial uses prototype and I have no idea how to convert it to jquery.

In my application.html.haml I have this:

%h3{:id => "alert", :class=>'alert-danger fade in', :style=>"padding: 10px;"}
  - unless current_announcements.empty?
    #announcement
      - for announcement in current_announcements
        %ul{:class=>'unstyled'}
          %li
            = h announcement.message
            = link_to "Hide this message", :url => "/javascripts/hide_announcement.js"#, :remote => true

Clicking the hide button is supposed to remove the view whilst also setting the announcement_hide_time to the current time. I have this in my javascript controller:

class JavascriptsController < ApplicationController

  respond_to :js

  attr_accessible :announcement_hide_time

  def hide_announcement
    session[:announcement_hide_time] = Time.now
  end
end

And this in my routes:

match ":controller/:action.:format"

The problem now is that in the railscast, it says I need the following in hide_announcement.js.rjs

page[:announcement].hide

Which I've replaced in hide_announcement.js.erb with:

$("#announcement").hide()

But when I click the link, I get no errors in the console and the message is not removed.


Solution

  • I’d advise you against emulating that Railscast. It’s from 2008 and things have changed a lot since then. Writing Javascript on the server for execution on the client is passé; the whole JavascriptsController idea feels cringeworthy to me.

    Instead, you could have the “Hide this message” link trigger an AJAX request on the client side that tells the server to stop showing the announcement, waits for a success-type response, and removes the message itself.

    I made a fiddle that shows a basic version of this. Note that it fakes the server response to the AJAX request, but all your application would have to do is return an HTTP success code.

    If your application is simple this would suffice, but eventually these jQuery events sprawl out of control and may call for a client-side framework like backbone.js to keep track of things.