Skip to content

Instantly share code, notes, and snippets.

@nesquena
Created October 1, 2010 23:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nesquena/607074 to your computer and use it in GitHub Desktop.
Save nesquena/607074 to your computer and use it in GitHub Desktop.
Simple pattern for handling jquery js in rails
// public/javascripts/application.js
// JQUERY example
// Accepts ev.foo, ev.bar, ev.html
$(document).bind('some:event', function(ev) {
// do something here
$('some-div').html(ev.html);
});
# lib/extensions/prototype_ext.rb
# NEEDS to be required manually in rails app)
# Uses debug library from here: http://benalman.com/projects/javascript-debug-console-log/
# This is for jquery library but can be done with prototype as well (Rails 2)
module ActionView::Helpers::PrototypeHelper
class JavaScriptGenerator
module GeneratorMethods
# will trigger a jquery custom event in order to cause
# some externally defined javascript to occur
#
# event_name = "custom:event" (the event to trigger)
# parameters = { :var => "value" } (the parameters to pass)
#
# example: page.trigger "custom:event"
#
def trigger(event_name, parameters={})
parameters.reverse_merge!(:type => event_name)
self << "$(document).trigger(#{parameters.to_json})"
self << "debug.info('triggered', #{event_name.inspect}, #{parameters.to_json})" if Rails.env.development?
end
end
end
end
# app/views/thing/some.js.rjs
# Jquery example
# This sends the necessary data to update the state
some_html = render(:partial => "foo")
page.trigger("some:event", :foo => 'bar', :bar => "baz", :html => some_html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment