Created
March 13, 2012 16:34
-
-
Save kazu69/2029789 to your computer and use it in GitHub Desktop.
Pjax(pushState + Ajax) with Sinatra and BackboneJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#encoding: UTF-8 | |
require 'rubygems' | |
require 'sinatra' | |
require 'erb' | |
require 'pp' | |
class Sinatra::Request | |
def pjax? | |
env['HTTP_X_PJAX'] || self['_pjax'] | |
end | |
end | |
get '/' do | |
erb :index | |
end | |
get '/pjax1' do | |
erb :pjax1, :layout => !request.pjax? | |
end | |
get '/pjax2' do | |
erb :pjax2, :layout => !request.pjax? | |
end | |
__END__ | |
@@ layout | |
<!DOCTYPE HTML> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Sinatra Pjax</title> | |
</head> | |
<body> | |
<div id="app"></div> | |
<%= yield %> | |
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script> | |
<script src='//documentcloud.github.com/underscore/underscore-min.js'></script> | |
<script src='//documentcloud.github.com/backbone/backbone-min.js'></script> | |
<script> | |
$(function(){ | |
$.ajaxSetup({ | |
beforeSend: function(xhr) { | |
xhr.setRequestHeader('X-PJAX', true); | |
} | |
}); | |
var Router = Backbone.Router.extend({ | |
initialize : function(){ | |
if(history && history.pushState) { | |
Backbone.history.start({pushState: true, root: "/"}); | |
} | |
else { | |
Backbone.history.start(); | |
} | |
} }); | |
var View = Backbone.View.extend({ | |
events : { | |
'click .get-pjax' : 'getPjax' | |
}, | |
el : $('body'), | |
initialize : function(){ | |
$('a').bind('click', function (e) { | |
e.preventDefault(); | |
router.navigate($(this).attr("href").substr(1), true); | |
}); | |
}, | |
getPjax : function(e){ | |
var path = $(e.currentTarget).attr("href").substr(1); | |
$("#content").load(path); | |
} | |
}); | |
window.view = new View(); | |
window.router = new Router; | |
$(window).bind("popstate", function(e){ | |
var id = location.pathname; | |
$('#content').text(''); | |
if('/' !== id) $('#content').load(id); | |
}); | |
}); | |
</script> | |
</body> | |
</html> | |
@@ index | |
<a href='#/pjax1' class="get-pjax" style="cursor:pointer;">click get pjax1</a><br> | |
<a href='#/pjax2' class="get-pjax" style="cursor:pointer;">click get pjax2</a> | |
<div id="content" style="margin-top:20px;"></div> | |
@@ pjax1 | |
<div>Pjax1 is OK!</div> | |
@@ pjax2 | |
<div>Pjax2 is OK!</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment