BigW Consortium Gitlab

autosave.js.coffee 704 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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?

17 18
    try
      text = window.localStorage.getItem @key
19
    catch e
20 21
      return

22
    @field.val text if text?.length > 0
23
    @field.trigger "input"
24 25 26 27 28 29

  save: ->
    return unless window.localStorage?

    text = @field.val()
    if text?.length > 0
30 31
      try
        window.localStorage.setItem @key, text
32 33 34 35 36 37
    else
      @reset()

  reset: ->
    return unless window.localStorage?

38
    try
39
      window.localStorage.removeItem @key