Skip to content

Instantly share code, notes, and snippets.

@mia-0032
Last active December 10, 2015 04:58
Show Gist options
  • Save mia-0032/4384811 to your computer and use it in GitHub Desktop.
Save mia-0032/4384811 to your computer and use it in GitHub Desktop.
PJAX通信でDOMをロードするクラス(CoffeeScript)
##PJAX通信でHTMLを取得してDOMを書き換える
class PjaxLoader
previousUrl: null
$container: null
$loading: null
constructor: () ->
@previousUrl = location.href
@$container = $('#content_area') ##書き換える対象のDOM
@$loading = $('#loading_image') ##ローディング表示の画像とか
$(window).bind('popstate', @_doPopstate)
##進んだり戻ったりするとこれが呼ばれる
_doPopstate: () =>
@_ajaxLoad(location.href) unless location.href is @previousUrl
return false
##ページと履歴を書き換える。パプリックなメソッドなので外部からURLを指定して実行。
load: (url) =>
window.history?.pushState?("", "", url)
@_ajaxLoad(url)
return false
##ajaxでロード
_ajaxLoad: (url) =>
@$loading.show()
@$container.empty().hide()
$.ajax(
url: url
cache: false
dataType: 'html'
beforeSend: (xhr) =>
xhr.setRequestHeader 'X-PJAX', 'true'
success: (data) =>
@$container.html(data).fadeIn(500)
@previousUrl = url
@$loading.hide())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment