Skip to content

Instantly share code, notes, and snippets.

@georgebrock
Created March 26, 2010 15:10
Show Gist options
  • Save georgebrock/344996 to your computer and use it in GitHub Desktop.
Save georgebrock/344996 to your computer and use it in GitHub Desktop.
Helpers for unobtrusive JavaScript in Rails applications
module JavaScriptHelper
# Call this in your views to indicate that a feature needs to be initialised
def use_javascript_for(feature)
@javascript_features ||= []
@javascript_features << feature
end
# Use this in your layout to add a list of classes to add to the body so that the JavaScript knows which features to initialised
def javascript_feature_classes
(@javascript_features || []).uniq.map{ |feature| "with-js-#{feature.downcase}" }.join(" ")
end
end
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Example layout</title>
<script type="text/javascript" src="/javascripts/my_site.js"></script>
</head>
<body class="<%= javascript_feature_classes %>">
<%= yield %>
</body>
</html>
var MySite = {};
jQuery(function($) {
for(key in MySite) {
if(MySite.hasOwnProperty(key)) {
if(typeof MySite[key]["global_init"] === "function") {
MySite[key].global_init($);
}
if(typeof MySite[key]["init"] === "function" && $("body").hasClass("with-js-" + key.toLowerCase())) {
MySite[key].init($);
}
}
}
});
MySite.Example = {
global_init: function($) {
// Run on all pages
},
init: function($) {
// Run on pages that call use_javascript_for("example")
}
};
<div class="example">
Some markup that can be enhanced with JavaScript
<% use_javascript_for("example") %>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment