Reputation: 18911
I am using Ruby on Rails 3.0.10 and jQuery 1.6. I am planning to write some JavaScript function in the application.js
file of my application so that I can approach the Unobtrusive JavaScript. However, I have some questions (those refer to the application.js
file):
Upvotes: 1
Views: 3508
Reputation: 9786
If I'm reading your question right you'd like to know how you should write your JS into the application.js file so that it fits into the vision of Unobtrusive Javascript.
Here's an example. Let's say you have a view with a link on the page that will let you type an answer into Javascript dialog box:
# app/views/questions/ask.html.erb
<h1>Question</h1>
<a href="#" class="question">Click here to see the question!</a>
Notice that the link is set to go nowhere. If the user doesn't have Javascript installed then this won't work. Now, in your application.js
file you hook into that <a>
tag via the class (I assume you're using jQuery):
// public/javascripts/application.js
$('.question').click(function() {
var name = prompt('What is your name?');
alert('Hello ' + name + '!');
});
That's it! This is "unobtrusive" because you don't see a bunch of Javascript code in your HTML. Now if you wanted to be a good Javascript citizen you could namespace your custom code and make it reusable throughout your app. Let's say you have lot of pages that can ask questions. You might want to refactor out the part the asks the question and have that simply return the answer back:
// public/javascripts/application.js
var CustomCode = {
askQuestion:function(text) {
return prompt(text);
}
};
$('.question').click(function() {
name = CustomCode.askQuestion('What is your name?');
alert('Hello ' + name + '!');
});
This is a pretty trivial refactor because it didn't really make anything more efficient, but let's say you wanted to do something with the answer before returning it to the user. Now you only write that code once (in the askQuestion()
method) and everyone gets the benefit.
You can see the code in action and play with it here: http://jsbin.com/arites
Upvotes: 3
Reputation: 4124
"How should I state JS functions?"
Write JS functions without enclosing in <script>
tags.
"What "kind of" functions should I add?" This file is good to use for code used more than once so you don't repeat yourself, but any code can be placed here to clean up your views.
"How should I organize functions?" Organize JS functions any way you want - you could comment sections to stay organized:
/*
Home Page Functions
*/
"How those function work with jQuery?" Jquery functions work like they normally would when you write them in the page header. ex:
$(function(){
alert('got to application.js!');
})
Note that in rails 3.1 things will be a little different...watch the railscast to get up to speed: upgrading to 3.1
Upvotes: 0