Created
March 26, 2010 15:10
-
-
Save georgebrock/344996 to your computer and use it in GitHub Desktop.
Helpers for unobtrusive JavaScript in Rails applications
This file contains 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
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 |
This file contains 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
<!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> |
This file contains 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
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") | |
} | |
}; |
This file contains 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
<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