Sha256: 3dd17568bd002422443826e22d6e84842ff43b51c765160682bfc6d1ad8f308b

Contents?: true

Size: 1.49 KB

Versions: 16

Compression:

Stored size: 1.49 KB

Contents

#### !!!UNSPECED ####
class Joosy.Resources.Watcher extends Joosy.Module
  @include Joosy.Modules.Events

  @cache: (cacheKey) -> @::__cacheKey = cacheKey
  @fetcher: (fetcher) -> @::__fetcher = fetcher

  @beforeLoad: (action) ->
    unless @::hasOwnProperty '__beforeLoads'
      @::__beforeLoads = [].concat @.__super__.__beforeLoads || []
    @::__beforeLoads.push action

  constructor: (cacheKey=false, fetcher=false) ->
    if Object.isFunction(cacheKey)
      fetcher  = cacheKey
      cacheKey = undefined

    @__fetcher = fetcher if fetcher
    @__cacheKey = cacheKey if cacheKey

  load: (callback) ->
    if @__cacheKey && localStorage[@__cacheKey]
      @data = @prepare(JSON.parse localStorage[@__cacheKey])
      @trigger 'changed'
      @refresh()
      callback? @
    else
      @__fetcher (result) =>
        localStorage[@__cacheKey] = JSON.stringify(result) if @__cacheKey
        @data = @prepare result
        @trigger 'changed'
        callback? @

  clone: ->
    copy = new @constructor(@__cacheKey, @__fetcher)
    copy.data = Object.clone(@data, true)
    copy.trigger 'changed'
    copy

  refresh: (callback) ->
    @__fetcher (result) =>
      localStorage[@__cacheKey] = JSON.stringify(result) if @__cacheKey
      @data = @prepare result
      @trigger 'changed'
      callback? @

  prepare: (data) ->
    if @__beforeLoads?
      data = bl.call(this, data) for bl in @__beforeLoads

    data

# AMD wrapper
if define?.amd?
  define 'joosy/resources/watcher', -> Joosy.Resources.Watcher

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
joosy-1.2.0.alpha.68 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.67 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.66 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.65 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.64 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.63 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.62 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.59 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.58 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.57 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.56 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.55 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.54 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.53 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.52 source/joosy/resources/watcher.coffee
joosy-1.2.0.alpha.51 source/joosy/resources/watcher.coffee