Recently, I decided to dive into the world of Ractive.js. My latest project involves creating a stop watch that continues running even if I navigate to another page. However, I've encountered an issue where the stopwatch disappears when I return to the original page after clicking elsewhere. Any thoughts on what my next steps should be?
Below are the snippets from my attempts:
Within my view:
<div class="modal-footer">
<div class="form-group">
<div class="pull-left">
Stopwatch: {{#stopWatch}} {{hours}} h: {{minutes}} m: {{seconds}} s{{/stopWatch}}
</div>
<button id="btnStart" class="btn btn-primary" type="button" on-click="startStopWatch">Start</button>
<button id="btnReset" class="btn btn-secondary" type="button" on-click="startStopWatch">Reset</button>
</div>
<label class="pull-left stopWatch"> Time Spent:</label>
</div>
My startStopWatch function:
function startStopWatch(ev, cfg) {
var rjs = this || cfg.rjs;
var $btn = $(ev.node);
var btnText = $btn.text();
var sg;
if (btnText === 'Start') {
$btn.html('Stop');
sg = new cmnDt.stopWatch();
sg.start(rjs, sg);
} else if (btnText === 'Stop'){
$btn.html('Start');
sg = ev.context.sw;
sg.stop(rjs, sg);
}
if (btnText === 'Reset' && ev.context.sw) {
sg = ev.context.sw;
sg.reset(rjs, sg);
$('#btnStart').html('Start');
}
}
My stopWatch function:
function stopWatch() {
var currentSeconds = 0;
var currentMinutes = 0;
var currentHours = 0;
var timer;
function start(rjs, sw) {
printTime(rjs, sw);
timer = setInterval(function () {
getTime();
printTime(rjs, sw);
}, 1000);
}
function getTime(rjs) {
currentSeconds = currentSeconds + 1;
if (currentSeconds === 60) {
currentMinutes += Math.round((currentSeconds) / 60);
currentSeconds = 0;
} else if (currentSeconds === 60 && currentMinutes === 60) {
currentMinutes = 0;
currentSeconds = 0;
currentHours += 1;
}
}
function printTime(rjs, sw) {
rjs.set({'sw': sw, 'stopWatch.seconds': currentSeconds,
'stopWatch.minutes': currentMinutes, 'stopWatch.hours': currentHours});
}
function stop(rjs, sw) {
clearInterval(timer);
printTime(rjs, sw);
$('.stopWatch').text(' Time Spent: ' + currentMinutes + ' m : ' + currentSeconds + ' s.');
}
function reset(rjs, sw) {
clearInterval(timer);
currentSeconds = 0;
currentMinutes = 0;
currentHours = 0;
printTime(rjs, sw);
}
return {
start: start,
stop: stop,
reset: reset
};
}