doc.coffee 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. class app.models.Doc extends app.Model
  2. # Attributes: name, slug, type, version, index_path, mtime
  3. constructor: ->
  4. super
  5. @reset @
  6. reset: (data) ->
  7. @resetEntries data.entries
  8. @resetTypes data.types
  9. return
  10. resetEntries: (entries) ->
  11. @entries = new app.collections.Entries(entries)
  12. @entries.each (entry) => entry.doc = @
  13. return
  14. resetTypes: (types) ->
  15. @types = new app.collections.Types(types)
  16. @types.each (type) => type.doc = @
  17. return
  18. fullPath: (path = '') ->
  19. path = "/#{path}" unless path[0] is '/'
  20. "/#{@slug}#{path}"
  21. fileUrl: (path) ->
  22. "#{app.config.docs_host}#{@fullPath(path)}"
  23. indexUrl: ->
  24. "#{app.indexHost()}/#{@index_path}?#{@mtime}"
  25. toEntry: ->
  26. new app.models.Entry
  27. doc: @
  28. name: @name
  29. path: 'index'
  30. findEntryByPathAndHash: (path, hash) ->
  31. if hash and entry = @entries.findBy 'path', "#{path}##{hash}"
  32. entry
  33. else if path is 'index'
  34. @toEntry()
  35. else
  36. @entries.findBy 'path', path
  37. load: (onSuccess, onError, options = {}) ->
  38. return if options.readCache and @_loadFromCache(onSuccess)
  39. callback = (data) =>
  40. @reset data
  41. onSuccess()
  42. @_setCache data if options.writeCache
  43. ajax
  44. url: @indexUrl()
  45. success: callback
  46. error: onError
  47. clearCache: ->
  48. app.store.del @slug
  49. return
  50. _loadFromCache: (onSuccess) ->
  51. return unless data = @_getCache()
  52. callback = =>
  53. @reset data
  54. onSuccess()
  55. setTimeout callback, 0
  56. true
  57. _getCache: ->
  58. return unless data = app.store.get @slug
  59. if data[0] is @mtime
  60. return data[1]
  61. else
  62. @clearCache()
  63. return
  64. _setCache: (data) ->
  65. app.store.set @slug, [@mtime, data]
  66. return