Download - Working with Javascript in Rails
Working with Javascriptin Rails
�70�BiweeklyLecture
2014-09-16
SeungKyunNam
- ROR Lab. Season 3 -
Agenda
Ajax:IntroductionUnobtrusiveJavascriptBuilt-inHelpersAjax:Server-SideConcernsTurbolinks
Ajax: Introduction
WhatisAjax:
AsynchronousJavascriptandXML
Ajax: Introduction
Theoriginofthetermcalled'Ajax'
byAdaptivePathBlogpost:Ajax:but...
ANewApproachtoWebApplications
Ajax: IntroductionUnderstandingRequest-ResponseCycle
Ajax: IntroductionClassicModelvsAJaxModel
Ajax: IntroductionSynchronousModelvsAsynchronousModel
Ajax: IntroductionDefiningAjax
Presentation:XHTMLandCSS->HTML5andCSS3DocumentObjectModelData:XMLandXSLT->(mostlyJSON)Carrier:XMLHttpRequestBindingeverythingtogether:Javascript
Ajax: IntroductionSampleCode
//COFFEESCRIPT$.ajax(url:"/test/lorem").done(html)->$("#results").appendhtml
//GeneratedJAVASCRIPT(function(){$.ajax({url:"/test/lorem"}).done(function(html){return$("#results").append(html);});
}).call(this);
Ajax: IntroductionDemo
Unobtrusive JavascriptThreemaingoals
ToseparateJavaScriptfromHTMLmarkup,aswellaskeepingmodulesofJavaScriptindependentofothermodules.UnobtrusiveJavaScriptshoulddegradegracefully-allcontentshouldbeavailablewithoutalloranyoftheJavaScriptrunningsuccessfully.UnobtrusiveJavaScriptshouldnotdegradetheaccessibilityoftheHTML,andideallyshouldimproveit,whethertheuserhaspersonaldisabilitiesorareusinganunusual,orunusuallyconfigured,browser.
Tip:TocomplieCoffeeScript
withouttop-levelfunctionsafetywrapper
#CompiletheJavascriptwithoutthetop-levelfunctionsafetywrapper#CoffeeScriptOption-bor--bareTilt::CoffeeScriptTemplate.default_bare=true
config/environment.rb
Traditional WayInlineJavascript
<ahref="#"onclick="this.style.backgroundColor='#009900';this.style.color='#FFFFFF'">Paintitgreen</a>
Traditional (Better) WayUsingFunctions
paintIt=(element,backgroundColor,textColor)->element.style.backgroundColor=backgroundColoriftextColor?element.style.color=textColor
<ahref="#"onclick="paintIt(this,'#990000')">Paintitred</a><ahref="#"onclick="paintIt(this,'#009900','#FFFFFF')">Paintitgreen</a>
Unobtrusive Way
paintIt=(element,backgroundColor,textColor)->element.style.backgroundColor=backgroundColoriftextColor?element.style.color=textColor
$->$("a[data-background-color]").click->backgroundColor=$(this).data("background-color")textColor=$(this).data["text-color"]paintIt(this,backgroundColor,textColor)
<ahref="#"data-background-color="#990000">Paintitred</a><ahref="#"data-background-color="#009900"data-text-color="#FFFFFF">Paintitgreen</a><ahref="#"data-background-color="#000099"data-text-color="#FFFFFF">Paintitblue</a>
Unobtrusive JavascriptDemo
Built-in HelpersRailsAjaxhelpersareintwoparts
Javascripthalf->rails.jsRubyhalf->addappropriatetagstoDOM
form_for
<%=form_for(@post,remote:true)do|f|%>...<%end%>
<!--GeneratedHTML--><formaccept-charset="UTF-8"action="/posts"class="new_post"data-remote="true"id="new_post"method="post">...</form>
form_forAddingAjaxEvent
$(document).ready->$("#new_post").on("ajax:success"),(e,data,status,xhr)->$("#new_post").appendxhr.responseText).bind"ajax:error",(e,data,status,error)->$("#new_post").append"<p>ERROR</p>"
form_tag
<%=form_tag('/posts',remote:true)%>
link_to
<%=link_to"apost",@post,remote:true%>
<!--GeneratedHTML--><ahref="/posts/1"data-remote="true">apost</a>
link_toAddingAjaxEvent
<%=link_to"DeletePost",@post,remote:true,method::delete%>
$->$("a[data-remote]").on"ajax:success",(e,data,status,xhr)->alert"Thepostwasdeleted."
button_to
<%=button_to"Apost",@post,remote:true%>
<!--GeneratedHTML--><formaction="/posts/1"class="button_to"data-remote="true"method="post"><div><inputtype="submit"value="Apost"></div></form>
Built-in HelpersDemo
Server-Side Concerns
Server-Side ConcernsbyExample
classUsersController<ApplicationControllerdefindex@users=User.all@user=User.newend
#...end
<b>Users</b>
<ulid="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 ConcernsbyExample
#...defcreate@user=User.new(params[:user])
respond_todo|format|[email protected]{redirect_to@user,notice:'Userwassuccessfullycreated.'}format.js{}format.json{renderjson:@user,status::created,location:@user}elseformat.html{renderaction:"new"}format.json{renderjson:@user.errors,status::unprocessable_entity}endendend#...
app/controllers/users_controller.rb
Server-Side ConcernsbyExample
$("<%=escape_javascript(render@user)%>").appendTo("#users")
app/views/users/create.js.erb
Server-Side ConcernsDemo
Turbolinks
Rails4DefaultTurbolinksGemUsesAjaxtospeeduppagerenderingPushState
TurbolinksHowitworks
attachesaclickhandlertoall<a>tagscheckifbrowsersupportsPushStateifso,
makeanAjaxrequestparsetheresponsereplacetheentire<body>changetheURLusingPushState
PushStateapartofHTML5History-API
<!doctypehtml><html><head><title>PushStateExample</title><scriptlanguage="javascript">
Using Turbolinks
#Turbolinksmakesfollowinglinksinyourwebapplicationfaster.#Readmore:https://github.com/rails/turbolinksgem'turbolinks'
Gemfile
//=requireturbolinks
app/assets/javascripts/applications.js
TurbolinksTodisableTurbolinksforcertainlinks
<ahref="..."data-no-turbolinks>Noturbolinkshere</a>.
usingdata-no-turbolinksattribute
TurbolinksTroubleshooting
$(document).ready->alert"pagehasloaded!"
#ThiseventwillnotworkbecauseofTurbolinks
$(document).on"page:change",->alert"pagehasloaded!"
#Thiswillwork!
TurbolinksDemo
Thank you