Created
October 1, 2010 23:56
-
-
Save nesquena/607074 to your computer and use it in GitHub Desktop.
Simple pattern for handling jquery js in rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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