Giter Site home page Giter Site logo

nanocomponent-cache's Introduction

NanocomponentCache stability

npm version build status downloads js-standard-style

Cache a nanocomponent instance by key. Creates a new instance if the key doesn't exist, otherwise returns the cached instance. A subclass of class-cache providing sane GC function defaults and a set of examples of intended usage. Optional LRU caching.

Usage

const NanocomponentCache = require('nanocomponent-cache')
const compare = require('nanocomponent/compare')
const Nanocomponent = require('nanocomponent')
const Tweet = require('twitter-component')
const assert = require('assert')
const html = require('bel')

class TweetList extends Nanocomponent {
  constructor () {
    super()
    this.tweetList = null
    // auto-eject last used instances over 100 total cached
    this.nc = new NanocomponentCache({ lru: 100 })
    // Register the components you will be caching
    this.nc.register(Tweet, {args: [{ placeholder: false }]} )
  }

  createElement (tweetList) {
    assert(isArray(tweetList), 'tweetList must be an array of tweet URLs')
    this.tweetList = tweetList // Cache a reference to tweetList
    const nc = this.nc
    return html`
      <div>
        ${tweetList.map(tweetURL => nc.get(tweetURL).render(tweetURL))}
      </div>
    `
  }

  update (tweetList) {
    assert(isArray(tweetList), 'tweetList must be an array of tweet URLs')
    return compare(this.tweetList, tweetList)
  }

  afterupdate (el) {
    // Periodically run the GC function to clean up unused instances.
    this.nc.gc()
  }
}

module.exports = TweetList

Examples

Installation

$ npm install nanocomponent-cache

API

NanocomponentCache = require('nanocomponent-cache')

Require NanocomponentCache class.

c = new NanocomponentCache([opts])

Create a new cache instance.

opts include:

{
  gc: (component) => !component.element // a default garbage collection function
  args: [] // Default args used for instantiating all classes,
  lru: 0 // Enable LRU gc by setting this to an integer greater than 0
}

c.register([typeKey = 'default'], SomeNanocomponent, [opts])

Define a Class for the optional typeKey. The default typeKey is default, which is used whenever a typeKey is omitted during gets and sets. opts include:

{
  gc: undefined // a typeKey specific GC function.
  args: undefined // default arguments instance arguments for `typeKey`. 
  // These options delegate to the top level options if left un-implemented
}

This is a shortcut for defining with a typeObject:

c.register({
  typeKey: { class: SomeNanocomponent, ...opts }
})

c.register({ typeObject })

Define class 'type's using a typeObject definition. A typeObject is an object who's keys define the type name which are associated with a Class and optionally args and a type specific gc function.

c.register({
  default: SomeNanocomponent, // SomeNanocomponent with no args or gc.  Uses instance gc function.
  baz: { class: SomeNanocomponent, ...opts }
})

Types are Object.assigned over previously registered types. The opts keys are the same as above.

c.unregister(...types)

Pass typeKeys as arguments to un-register them. Instances are untouched during this process.

c.get(key, [Class || typeKey], [opts])

The primary method used to retrieve and create instances. Return instance of Class or defined type class at key. If an instance does not yet exist at key, it will be instantiated with args along with a key specific gc function. If type is not defined, this method will throw.

Omitting optional method arguments delegates to the next most specific option.

c.get('some-key') // Return or create the 'default' Class
c.get('some-key', {args: ['arg0', 'arg2']})
c.get('some-key', null, {args: ['arg0', 'arg2']}) // Return the default registered class with specific args
c.get('some-key', 'some-type', { args: ['arg0', 'arg2'] }) // Return the `some-type` class at `some-key`.
c.get('some-key', SomeOtherNanocomponent, { args: ['arg0', 'arg2'], gc: instance => true })

If key is already instantiated, args is ignored. Pass changing properties as subsequent calls to the returned instance. If type or Class changes, the key instance is re-instantiated.

c.set(key, [Class || type], [opts])

Force instantiate the class instance at key. Follows the same override behavior as get. If you must change args on a key, this is the safest way to do that.

Returns the newly created instance.

c.gc()

Run the various gc functions defined. For each key, only the most specific gc function set is run. Return true from the gc functions to garbage collect that instance, and false to preserve.

This is used to clean out instances you no longer need. Because this iterates over all keys with instances, run this often enough so that the key set doesn't grow too large but not too often to create unnecessary delays in render loops.

c.clear()

Clear all key instances. The gc functions for each instance will be run receiving the following signature: (instance, key, true) => {}. If your instance needs to let go of resources, watch for the second argument to equal true, indicating tht the instance will be deleted.

c.delete(key)

Delete specific key instance. Will run the gc function passing true as the second argument ((instance, key, true) => {}).

c.has(key)

Return true if key exists.

See examples for more details.

Examples

See the examples folder for various ideas on how to use this library.

See Also

License

MIT

nanocomponent-cache's People

Contributors

bcomnes avatar

Stargazers

Valery Orloff avatar Manan Rana avatar  avatar Yosh avatar

Watchers

 avatar James Cloos avatar  avatar

nanocomponent-cache's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.