summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/autosave.js.coffee
blob: 28f8e103664110f8ba3bf8c4b6b9a663cb06c734 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class @Autosave
  constructor: (field, key) ->
    @field = field

    key = key.join("/") if key.join?
    @key = "autosave/#{key}"

    @field.data "autosave", this

    @restore()

    @field.on "input", => @save()

  restore: ->
    return unless window.localStorage?

    try
      text = window.localStorage.getItem @key
    catch e
      return

    @field.val text if text?.length > 0
    @field.trigger "input"

  save: ->
    return unless window.localStorage?

    text = @field.val()
    if text?.length > 0
      try
        window.localStorage.setItem @key, text
    else
      @reset()

  reset: ->
    return unless window.localStorage?

    try
      window.localStorage.removeItem @key