Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!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