Created
December 15, 2015 03:10
-
-
Save jgaskins/6624fbb7c6d678439b8c to your computer and use it in GitHub Desktop.
Graceful degradation from pushState routing to fragment-based routing
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
class Router | |
def initialize | |
if `window.location.pushState === undefined` | |
@location = FragmentLocation.new | |
if !has_fragment? | |
@location.copy_path_to_fragment! | |
end | |
else | |
@location = PushStateLocation.new | |
if has_fragment? | |
@location.move_fragment_to_path! | |
end | |
end | |
end | |
end | |
class Location | |
def navigate_to path | |
raise NotImplementedError, 'You must use a subclass of `Location`' | |
end | |
end | |
class FragmentLocation < Location | |
def navigate_to path | |
%x{ window.location.hash = path } | |
end | |
def copy_path_to_fragment! | |
%x{ window.location.hash = window.location.pathname } | |
end | |
end | |
class PushStateLocation < Location | |
def navigate_to path | |
%x{ window.history.pushState({}}, '', path) } | |
end | |
def move_fragment_to_path! | |
%x{ window.history.replaceState({}, '', hash) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment