Skip to content

Commit

Permalink
Merge pull request #35 from Shopify/add_ability_to_use_csrf_tokens
Browse files Browse the repository at this point in the history
Adding turbograft:remote:init Event
  • Loading branch information
pseudomuto committed Nov 11, 2014
2 parents 115ba88 + dddce45 commit a9b1d94
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions lib/assets/javascripts/turbograft/remote.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class TurboGraft.Remote
xhr = new XMLHttpRequest
xhr.open(actualRequestType, @opts.httpUrl, true)
xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml')
triggerEvent('turbograft:remote:init', xhr: xhr)

xhr.addEventListener 'loadstart', =>
triggerEvent 'turbograft:remote:start',
Expand Down
6 changes: 4 additions & 2 deletions test/example/app/views/pages/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@
</ul>
<p>It emits a few events:</p>
<ul>
<li><code>turbograft:remote:start</code>: before XHR is sent</li>
<li><code>turbograft:remote:init</code>: before XHR is sent</li>
<li><code>turbograft:remote:start</code>: when XHR is sent</li>
<li><code>turbograft:remote:always</code>: always fires when XHR is done</li>
<li><code>turbograft:remote:success</code>: always fires when XHR was successful</li>
<li><code>turbograft:remote:fail</code>: always fires when XHR failed</li>
Expand Down Expand Up @@ -184,7 +185,8 @@
</ul>
<p>It emits a few events:</p>
<ul>
<li><code>turbograft:remote:start</code>: before XHR is sent</li>
<li><code>turbograft:remote:init</code>: before XHR is sent</li>
<li><code>turbograft:remote:start</code>: when XHR is sent</li>
<li><code>turbograft:remote:always</code>: always fires when XHR is done</li>
<li><code>turbograft:remote:success</code>: always fires when XHR was successful</li>
<li><code>turbograft:remote:fail</code>: always fires when XHR failed</li>
Expand Down
13 changes: 13 additions & 0 deletions test/javascripts/remote_test.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@ describe 'Remote', ->
assert.equal "POST", request.method

describe 'TurboGraft events', ->

it 'allows turbograft:remote:init to set a header', ->
$(document).one "turbograft:remote:init", (event) ->
event.originalEvent.data.xhr.setRequestHeader("X-CSRF-Token", "anything")

server = sinon.fakeServer.create()
remote = new TurboGraft.Remote
httpRequestType: "POST"
httpUrl: "/foo/bar"

request = server.requests[0]
assert.equal "anything", request.requestHeaders["X-CSRF-Token"]

it 'will trigger turbograft:remote:start on start with the XHR as the data', (done) ->
$(document).one "turbograft:remote:start", (ev) ->
assert.equal "/foo/bar", ev.originalEvent.data.xhr.url
Expand Down

0 comments on commit a9b1d94

Please sign in to comment.