Caching collections in backbone.js?

前端 未结 6 919
暖寄归人
暖寄归人 2021-02-03 12:50

What would be the best way to ensure that my collection stays cached and thereby only gets fetched once?

Should I implement some sort of cache layer? Should I share the

6条回答
  •  日久生厌
    2021-02-03 13:25

    I ended up doing something similar to ProTom's solution. Instead of dynamically initializing a collection based on the name, I decided to just use a function to setup the collection. Through my application, I needed to initialize collections differently depending on where it was coming from. This proved to be the best way for my needs. Here's the CoffeeScript:

    Cache:

    cachedCollections: {}
    getCollection: (key, block) ->
      collection = @cachedCollections[key]
      return collection if collection
      collection = block()
      @cachedCollections[key] = collection
      collection
    

    Usage:

    commentCollection = getCollection "comments-#{postId}", ->
      collection = new CommentCollection
      collection.url = "/api/posts/#{postId}/comments"
      collection
    

提交回复
热议问题