- ROR Lab. Season 3 - 
 70 Biweekly Lecture 
Working with Javascript 
in Rails 
2014-09-16 
SeungKyun Nam
Agenda 
Ajax: Introduction 
Unobtrusive Javascript 
Built-in Helpers 
Ajax: Server-Side Concerns 
Turbolinks
Ajax: Introduction 
What is Ajax: 
Asynchronous 
Javascript 
and 
XML
Ajax: Introduction 
The origin of the term called 'Ajax' 
by Adaptive Path 
Blog post: Ajax: 
but ... 
A New Approach to Web Applications
Ajax: Introduction 
Understanding Request-Response Cycle
Ajax: Introduction 
Classic Model vs AJax Model
Ajax: Introduction 
Synchronous Model vs Asynchronous Model
Ajax: Introduction 
Defining Ajax 
Presentation: XHTML and CSS - HTML5 and CSS3 
Document Object Model 
Data: XML and XSLT - (mostly JSON) 
Carrier: XMLHttpRequest 
Binding everything together: Javascript
Ajax: Introduction 
Sample Code 
// COFFEESCRIPT 
$.ajax(url: /test/lorem).done (html) - 
$(#results).append html 
// Generated JAVASCRIPT 
(function() { 
$.ajax({ 
url: /test/lorem 
}).done(function(html) { 
return $(#results).append(html); 
}); 
}).call(this);
Ajax: Introduction 
Demo
Unobtrusive Javascript 
Three main goals 
To separate JavaScript from HTML markup, as well as 
keeping modules of JavaScript independent of other 
modules. 
Unobtrusive JavaScript should degrade gracefully - all 
content should be available without all or any of the 
JavaScript running successfully. 
Unobtrusive JavaScript should not degrade the 
accessibility of the HTML, and ideally should improve it, 
whether the user has personal disabilities or are using an 
unusual, or unusually configured, browser.
Tip: 
To complie CoffeeScript 
without top-level function safety wrapper 
# Compile the Javascript without the top-level function safety wrapper 
# CoffeeScript Option -b or --bare 
Tilt::CoffeeScriptTemplate.default_bare = true 
config/environment.rb
Traditional Way 
Inline Javascript 
a href=# onclick=this.style.backgroundColor='#009900';this.style.color='#FFFFFF' 
Paint it green 
/a
Traditional (Better) Way 
Using Functions 
paintIt = (element, backgroundColor, textColor) - 
element.style.backgroundColor = backgroundColor 
if textColor? 
element.style.color = textColor 
a href=# onclick=paintIt(this, '#990000')Paint it red/a 
a href=# onclick=paintIt(this, '#009900', '#FFFFFF')Paint it green/a
Unobtrusive Way 
paintIt = (element, backgroundColor, textColor) - 
element.style.backgroundColor = backgroundColor 
if textColor? 
element.style.color = textColor 
$ - 
$(a[data-background-color]).click - 
backgroundColor = $(this).data(background-color) 
textColor = $(this).data[text-color] 
paintIt(this, backgroundColor, textColor) 
a href=# data-background-color=#990000Paint it red/a 
a href=# data-background-color=#009900 data-text-color=#FFFFFFPaint it green/a 
a href=# data-background-color=#000099 data-text-color=#FFFFFFPaint it blue/a
Unobtrusive Javascript 
Demo
Built-in Helpers 
Rails Ajax helpers are in two parts 
Javascript half - rails.js 
Ruby half - add appropriate tags to DOM
form_for 
%= form_for(@post, remote: true) do |f| % 
... 
% end % 
!-- Generated HTML -- 
form accept-charset=UTF-8 
action=/posts 
class=new_post 
data-remote=true 
id=new_post method=post 
... 
/form
form_for 
Adding Ajax Event 
$(document).ready - 
$(#new_post).on(ajax:success), (e, data, status, xhr) - 
$(#new_post).append xhr.responseText 
).bind ajax:error, (e, data, status, error) - 
$(#new_post).append pERROR/p
form_tag 
%= form_tag('/posts', remote: true) %
link_to 
%= link_to a post, @post, remote: true % 
!-- Generated HTML -- 
a href=/https/www.slideshare.net/posts/1 data-remote=truea post/a
link_to 
Adding Ajax Event 
%= link_to Delete Post, @post, remote: true, method: :delete % 
$ - 
$(a[data-remote]).on ajax:success, (e, data, status, xhr) - 
alert The post was deleted.
button_to 
%= button_to A post, @post, remote: true % 
!-- Generated HTML -- 
form action=/posts/1 class=button_to data-remote=true method=post 
divinput type=submit value=A post/div 
/form
Built-in Helpers 
Demo
Server-Side Concerns
Server-Side Concerns 
by Example 
class UsersController  ApplicationController 
def index 
@users = User.all 
@user = User.new 
end 
# ... 
end 
bUsers/b 
ul id=users 
li /li 
/ul 
br 
br 
app/views/users/index.html.erb 
app/controllers/users_controller.rb 
li /li 
app/views/users/_user.html.erb
Server-Side Concerns 
by Example 
# ... 
def create 
@user = User.new(params[:user]) 
respond_to do |format| 
if @user.save 
format.html { redirect_to @user, notice: 'User was successfully created.' } 
format.js {} 
format.json { render json: @user, status: :created, location: @user } 
else 
format.html { render action: new } 
format.json { render json: @user.errors, status: :unprocessable_entity } 
end 
end 
end 
# ... 
app/controllers/users_controller.rb
Server-Side Concerns 
by Example 
$(%= escape_javascript(render @user) %).appendTo(#users) 
app/views/users/create.js.erb
Server-Side Concerns 
Demo
Turbolinks 
Rails 4 Default 
Turbolinks Gem 
Uses Ajax to speed up page rendering 
PushState
Turbolinks 
How it works 
attaches a click handler to all a tags 
check if browser supports PushState 
if so, 
make an Ajax request 
parse the response 
replace the entire body 
change the URL using PushState
PushState 
a part of HTML5 History-API 
!doctype html 
html 
head 
titlePushState Example/title 
script language=javascript
Using Turbolinks 
# Turbolinks makes following links in your web application faster. 
# Read more: https://github.com/rails/turbolinks 
gem 'turbolinks' 
Gemfile 
//= require turbolinks 
app/assets/javascripts/applications.js
Turbolinks 
To disable Turbolinks for certain links 
a href=... data-no-turbolinksNo turbo links here/a. 
using data-no-turbolinks attribute
Turbolinks 
Troubleshooting 
$(document).ready - 
alert page has loaded! 
# This event will not work because of Turbolinks 
$(document).on page:change, - 
alert page has loaded! 
# This will work!
Turbolinks 
Demo
Thank you

More Related Content

PDF
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
PDF
jQuery and Rails: Best Friends Forever
PDF
Get AngularJS Started!
PPTX
The Chaos Tools Suite
DOC
Soa lab 3
PPTX
Template syntax in Angular 2.0
KEY
Leveraging the Chaos tool suite for module development
PDF
前后端mvc经验 - webrebuild 2011 session
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
jQuery and Rails: Best Friends Forever
Get AngularJS Started!
The Chaos Tools Suite
Soa lab 3
Template syntax in Angular 2.0
Leveraging the Chaos tool suite for module development
前后端mvc经验 - webrebuild 2011 session

What's hot (20)

PPTX
Angular directive filter and routing
PDF
Count to 10 and Say Yes
PDF
CFUGbe talk about Angular JS
PPTX
Javascript validating form
PPTX
Dart and AngularDart
KEY
Django Admin: Widgetry & Witchery
PPTX
Modules and injector
PPTX
Emberjs as a rails_developer
PPTX
Building a dashboard using AngularJS
PPT
jQuery Performance Rules
PDF
Oleksandr Masovets. Forms in Drupal. Drupal Camp Kyiv 2011
PPTX
Angular 2 Architecture (Bucharest 26/10/2016)
PPTX
DJango admin interface
PPT
symfony & jQuery (phpDay)
DOCX
Validation using javascripts by karan chanana
PPTX
Jsp config implicit object
PPTX
AngularJS in 60ish Minutes
PDF
ActiveResource & REST
PDF
WordCamp Geneva Presentation - Customising WordPress' Admin Panel - 19 Nov. 2016
PPTX
Jquery Complete Presentation along with Javascript Basics
Angular directive filter and routing
Count to 10 and Say Yes
CFUGbe talk about Angular JS
Javascript validating form
Dart and AngularDart
Django Admin: Widgetry & Witchery
Modules and injector
Emberjs as a rails_developer
Building a dashboard using AngularJS
jQuery Performance Rules
Oleksandr Masovets. Forms in Drupal. Drupal Camp Kyiv 2011
Angular 2 Architecture (Bucharest 26/10/2016)
DJango admin interface
symfony & jQuery (phpDay)
Validation using javascripts by karan chanana
Jsp config implicit object
AngularJS in 60ish Minutes
ActiveResource & REST
WordCamp Geneva Presentation - Customising WordPress' Admin Panel - 19 Nov. 2016
Jquery Complete Presentation along with Javascript Basics
Ad

Similar to Working with Javascript in Rails (20)

PDF
jQuery Presentation to Rails Developers
PDF
Devdays Seattle jQuery Intro for Developers
PDF
Rails is not just Ruby
PDF
Write Less Do More
PDF
Cleaner, Leaner, Meaner: Refactoring your jQuery
PDF
jQuery and Rails, Sitting in a Tree
PDF
Ajax Rails
 
PDF
Unobtrusive JavaScript
KEY
Week 4 - jQuery + Ajax
PDF
Stack Overflow Austin - jQuery for Developers
PPTX
Rails Concerns and Turbolinks
PDF
Jquery In Rails
KEY
NinjaScript 2010-10-14
PDF
jQuery-1-Ajax
PDF
jQuery-1-Ajax
PDF
Microsoft PowerPoint - <b>jQuery</b>-1-Ajax.pptx
PDF
<img src="../i/r_14.png" />
PPT
jQuery Presentation - Refresh Events
PPT
Eugene Andruszczenko: jQuery
PDF
UJS in Rails 3
jQuery Presentation to Rails Developers
Devdays Seattle jQuery Intro for Developers
Rails is not just Ruby
Write Less Do More
Cleaner, Leaner, Meaner: Refactoring your jQuery
jQuery and Rails, Sitting in a Tree
Ajax Rails
 
Unobtrusive JavaScript
Week 4 - jQuery + Ajax
Stack Overflow Austin - jQuery for Developers
Rails Concerns and Turbolinks
Jquery In Rails
NinjaScript 2010-10-14
jQuery-1-Ajax
jQuery-1-Ajax
Microsoft PowerPoint - <b>jQuery</b>-1-Ajax.pptx
<img src="../i/r_14.png" />
jQuery Presentation - Refresh Events
Eugene Andruszczenko: jQuery
UJS in Rails 3
Ad

Recently uploaded (20)

PPTX
Chapter 5: Probability Theory and Statistics
PDF
Zenith AI: Advanced Artificial Intelligence
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Comparative analysis of machine learning models for fake news detection in so...
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Five Habits of High-Impact Board Members
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
STKI Israel Market Study 2025 version august
PDF
UiPath Agentic Automation session 1: RPA to Agents
PDF
A review of recent deep learning applications in wood surface defect identifi...
PPTX
2018-HIPAA-Renewal-Training for executives
DOCX
search engine optimization ppt fir known well about this
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PPTX
Benefits of Physical activity for teenagers.pptx
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
sustainability-14-14877-v2.pddhzftheheeeee
Chapter 5: Probability Theory and Statistics
Zenith AI: Advanced Artificial Intelligence
Module 1.ppt Iot fundamentals and Architecture
OpenACC and Open Hackathons Monthly Highlights July 2025
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Comparative analysis of machine learning models for fake news detection in so...
1 - Historical Antecedents, Social Consideration.pdf
Five Habits of High-Impact Board Members
A contest of sentiment analysis: k-nearest neighbor versus neural network
STKI Israel Market Study 2025 version august
UiPath Agentic Automation session 1: RPA to Agents
A review of recent deep learning applications in wood surface defect identifi...
2018-HIPAA-Renewal-Training for executives
search engine optimization ppt fir known well about this
Consumable AI The What, Why & How for Small Teams.pdf
Final SEM Unit 1 for mit wpu at pune .pptx
Taming the Chaos: How to Turn Unstructured Data into Decisions
Benefits of Physical activity for teenagers.pptx
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
sustainability-14-14877-v2.pddhzftheheeeee

Working with Javascript in Rails

  • 1. - ROR Lab. Season 3 - 70 Biweekly Lecture Working with Javascript in Rails 2014-09-16 SeungKyun Nam
  • 2. Agenda Ajax: Introduction Unobtrusive Javascript Built-in Helpers Ajax: Server-Side Concerns Turbolinks
  • 3. Ajax: Introduction What is Ajax: Asynchronous Javascript and XML
  • 4. Ajax: Introduction The origin of the term called 'Ajax' by Adaptive Path Blog post: Ajax: but ... A New Approach to Web Applications
  • 5. Ajax: Introduction Understanding Request-Response Cycle
  • 6. Ajax: Introduction Classic Model vs AJax Model
  • 7. Ajax: Introduction Synchronous Model vs Asynchronous Model
  • 8. Ajax: Introduction Defining Ajax Presentation: XHTML and CSS - HTML5 and CSS3 Document Object Model Data: XML and XSLT - (mostly JSON) Carrier: XMLHttpRequest Binding everything together: Javascript
  • 9. Ajax: Introduction Sample Code // COFFEESCRIPT $.ajax(url: /test/lorem).done (html) - $(#results).append html // Generated JAVASCRIPT (function() { $.ajax({ url: /test/lorem }).done(function(html) { return $(#results).append(html); }); }).call(this);
  • 11. Unobtrusive Javascript Three main goals To separate JavaScript from HTML markup, as well as keeping modules of JavaScript independent of other modules. Unobtrusive JavaScript should degrade gracefully - all content should be available without all or any of the JavaScript running successfully. Unobtrusive JavaScript should not degrade the accessibility of the HTML, and ideally should improve it, whether the user has personal disabilities or are using an unusual, or unusually configured, browser.
  • 12. Tip: To complie CoffeeScript without top-level function safety wrapper # Compile the Javascript without the top-level function safety wrapper # CoffeeScript Option -b or --bare Tilt::CoffeeScriptTemplate.default_bare = true config/environment.rb
  • 13. Traditional Way Inline Javascript a href=# onclick=this.style.backgroundColor='#009900';this.style.color='#FFFFFF' Paint it green /a
  • 14. Traditional (Better) Way Using Functions paintIt = (element, backgroundColor, textColor) - element.style.backgroundColor = backgroundColor if textColor? element.style.color = textColor a href=# onclick=paintIt(this, '#990000')Paint it red/a a href=# onclick=paintIt(this, '#009900', '#FFFFFF')Paint it green/a
  • 15. Unobtrusive Way paintIt = (element, backgroundColor, textColor) - element.style.backgroundColor = backgroundColor if textColor? element.style.color = textColor $ - $(a[data-background-color]).click - backgroundColor = $(this).data(background-color) textColor = $(this).data[text-color] paintIt(this, backgroundColor, textColor) a href=# data-background-color=#990000Paint it red/a a href=# data-background-color=#009900 data-text-color=#FFFFFFPaint it green/a a href=# data-background-color=#000099 data-text-color=#FFFFFFPaint it blue/a
  • 17. Built-in Helpers Rails Ajax helpers are in two parts Javascript half - rails.js Ruby half - add appropriate tags to DOM
  • 18. form_for %= form_for(@post, remote: true) do |f| % ... % end % !-- Generated HTML -- form accept-charset=UTF-8 action=/posts class=new_post data-remote=true id=new_post method=post ... /form
  • 19. form_for Adding Ajax Event $(document).ready - $(#new_post).on(ajax:success), (e, data, status, xhr) - $(#new_post).append xhr.responseText ).bind ajax:error, (e, data, status, error) - $(#new_post).append pERROR/p
  • 21. link_to %= link_to a post, @post, remote: true % !-- Generated HTML -- a href=/https/www.slideshare.net/posts/1 data-remote=truea post/a
  • 22. link_to Adding Ajax Event %= link_to Delete Post, @post, remote: true, method: :delete % $ - $(a[data-remote]).on ajax:success, (e, data, status, xhr) - alert The post was deleted.
  • 23. button_to %= button_to A post, @post, remote: true % !-- Generated HTML -- form action=/posts/1 class=button_to data-remote=true method=post divinput type=submit value=A post/div /form
  • 26. Server-Side Concerns by Example class UsersController ApplicationController def index @users = User.all @user = User.new end # ... end bUsers/b ul id=users li /li /ul br br app/views/users/index.html.erb app/controllers/users_controller.rb li /li app/views/users/_user.html.erb
  • 27. Server-Side Concerns by Example # ... def create @user = User.new(params[:user]) respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.js {} format.json { render json: @user, status: :created, location: @user } else format.html { render action: new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # ... app/controllers/users_controller.rb
  • 28. Server-Side Concerns by Example $(%= escape_javascript(render @user) %).appendTo(#users) app/views/users/create.js.erb
  • 30. Turbolinks Rails 4 Default Turbolinks Gem Uses Ajax to speed up page rendering PushState
  • 31. Turbolinks How it works attaches a click handler to all a tags check if browser supports PushState if so, make an Ajax request parse the response replace the entire body change the URL using PushState
  • 32. PushState a part of HTML5 History-API !doctype html html head titlePushState Example/title script language=javascript
  • 33. Using Turbolinks # Turbolinks makes following links in your web application faster. # Read more: https://github.com/rails/turbolinks gem 'turbolinks' Gemfile //= require turbolinks app/assets/javascripts/applications.js
  • 34. Turbolinks To disable Turbolinks for certain links a href=... data-no-turbolinksNo turbo links here/a. using data-no-turbolinks attribute
  • 35. Turbolinks Troubleshooting $(document).ready - alert page has loaded! # This event will not work because of Turbolinks $(document).on page:change, - alert page has loaded! # This will work!