Created
January 4, 2016 14:51
-
-
Save chuck0523/6c9ac6514888f22bc95a to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>React風のjQuery</title> | |
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> | |
</head> | |
<body> | |
<div> | |
Position <span id="current"></span> of <span id="final"></span> | |
</div> | |
<div id="number"></div> | |
<button id="inc">+1</button> | |
<button id="back">Back</button> | |
<button id="next">Next</button> | |
<script> | |
var state = { number: 0}; | |
var time; | |
$(function () { | |
var stored_state = JSON.parse(localStorage.getItem('state')); | |
if(stored_state) { | |
state = stored_state; | |
} | |
updateUI(); | |
}); | |
function updateUI(loading) { | |
if(!loading) saveState(); | |
$('#number').text(state.number); | |
localStorage.setItem('state', JSON.stringify(state)); | |
} | |
$('#inc').click(function() { | |
state.number++; | |
updateUI(); | |
}); | |
function updateTimeUI() { | |
$('#current').text(time.pos + 1); | |
$('#final').text(time.history.length); | |
$('#back').prop('disabled', time.pos <= 0); | |
$('#next').prop('disabled', time.pos >= time.history.length - 1); | |
} | |
function saveState() { | |
time = time || {history: [], pos: -1}; | |
// delete alternate future history | |
time.history.splice(time.pos+1); | |
// push state to history | |
time.history.push(deepcopy(state)); | |
time.pos++; | |
updateTimeUI(); | |
} | |
$('#back').on('click', function () { | |
// history上の位置を移動 | |
time.pos--; | |
updateTimeUI(); | |
// historyから読んだ状態を読み出す | |
state = deepcopy(time.history[time.pos]); | |
updateUI(true); | |
}) | |
$('#next').on('click', function () { | |
time.pos++; | |
updateTimeUI(); | |
// historyから読んだ状態を読み出す | |
state = deepcopy(time.history[time.pos]); | |
updateUI(true); | |
}) | |
function deepcopy(obj) { | |
return $.extend(true, {}, obj); | |
} | |
</script> | |
</body> | |
</html> | |
<!-- code is cited from http://postd.cc/boiling-react-down-to-a-few-lines-in-jquery/ --> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment