clartaq
clartaq

Reputation: 5372

"Autosave" Functionality in ClojureScript

I'd like to add an "autosave" feature to a Reagent form in a ClojureScript function. In Clojure, I usually make something out of a ScheduledExecutorService. Since that isn't available in ClojureScript, I came up with the following.

(def delay-handle (atom nil))

(defn clear-autosave-delay! []
  (.clearTimeout js/window @delay-handle))

(defn start-autosave-delay!
  [doc-save-fn delay-ms page-map-atom]
  (reset! delay-handle (.setTimeout js/window doc-save-fn delay-ms page-map-atom)))

(defn change-watcher!
  [doc-save-fn page-map-atom]
  (let [delay (* 1000 (get-in @page-map-atom [:options :editor_autosave_interval]))]
    (when (pos? delay)
      (clear-autosave-delay!)
      (start-autosave-delay! doc-save-fn delay page-map-atom))))

I put the change-watcher! function in the Reagent :on-change handlers for the input controls. Whenever a change occurs, it resets the delay. If the delay expires, the doc-save-fn is called to do the save.

It seems to work Ok, but isn't very "Clojuresque." Is there a more idiomatic way to write this?​

Upvotes: 0

Views: 160

Answers (1)

Chris Callwait
Chris Callwait

Reputation: 140

Use debouncer for this issue. It's pretty simple and does same

(goog.functions.debounce auto-save-action 1000)

Upvotes: 1

Related Questions