BigW Consortium Gitlab

autosave.js.coffee 707 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 19 20 21
    try
      text = window.localStorage.getItem @key
    catch
      return

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

  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 39
    try 
      window.localStorage.removeItem @key