From 73744a9c6840fb0ba6f285ca81f9fba75ec22d5f Mon Sep 17 00:00:00 2001 From: David Gay Date: Tue, 4 May 2021 17:55:28 -0400 Subject: Initial draft of timer setup, with results outputting and items being awarded --- .../controllers/activities/timer_controller.js | 43 ++++++++++++++++++++++ app/javascript/packs/application.js | 7 ++++ 2 files changed, 50 insertions(+) create mode 100644 app/javascript/controllers/activities/timer_controller.js (limited to 'app/javascript') diff --git a/app/javascript/controllers/activities/timer_controller.js b/app/javascript/controllers/activities/timer_controller.js new file mode 100644 index 0000000..11057c0 --- /dev/null +++ b/app/javascript/controllers/activities/timer_controller.js @@ -0,0 +1,43 @@ +import { Controller } from "stimulus"; +import Rails from "@rails/ujs"; + +export default class extends Controller { + static targets = [ "timer" ]; + + static values = { + start: Number, + } + + initialize() { + this.counter = this.startValue; + this.timerTarget.textContent = this.counter; + } + + connect() { + this.startUpdating(); + } + + disconnect() { + this.stopUpdating(); + } + + startUpdating() { + this.timerInterval = setInterval(() => { + if (this.counter > 0) { + this.timerTarget.textContent = this.counter.toString(); + this.counter--; + } else if (this.counter === 0) { + Rails.ajax({ + type: "POST", + url: "/finish_activity", + }); + } + }, 1000); + } + + stopUpdating() { + if (this.timerInterval) { + clearInterval(this.timerInterval); + } + } +} diff --git a/app/javascript/packs/application.js b/app/javascript/packs/application.js index 856724b..a18528e 100644 --- a/app/javascript/packs/application.js +++ b/app/javascript/packs/application.js @@ -13,3 +13,10 @@ Turbolinks.start() ActiveStorage.start() require("stylesheets/application.css") + +// Stimulus +import { Application } from "stimulus" +import { definitionsFromContext } from "stimulus/webpack-helpers" +const application = Application.start() +const context = require.context("../controllers", true, /\.js$/) +application.load(definitionsFromContext(context)) -- cgit v1.2.3