Git Product home page Git Product logo

locache's Introduction

locache

JavaScript framework for client side caching in the browser using DOM Storage with expiring values. With a memcache inspired API usage is very simple. Locache has no dependencies and is very small.

locache gracefully degrades when the browser doesn't support localStorage. Usually this will be IE6 or IE7, you wont get any errors, but caching attempts will be silently dropped and lookups will always appear to be a cache miss.

When and why?

Locache.js isn't a replacement for cache headers, and won't replace real server side caching. However, locache can be used to help speed up pages By caching results from APIs that you can't control or by caching complex structures created in JavaScript to avoid recreating. This works well with Models in backbone or rendered templates for example.

Setting, getting and removing values

Values can be stored one at a time as shown below, these values will never expire and will only be removed when you (or the browser) removes them.

locache.set("my_key", "my_value")

locache.get("my_key")
// my_value

locache.remove("my_key")

When you store an object, that's what you'll get back. For example, a number:

locache.set("counter", 1)
typeof locache.get("counter")
// number

Storing complex objects isn't a problem too. Just make sure they are JSON serializable.

locache.set('user', {
    'name': "Dougal Matthews",
    'alias': d0ugal
})

var result = locache.get('user')

//{
//    'name': "Dougal Matthews",
//    'alias': d0ugal
//}

You can also perform batch operations.

locache.setMany({
    'name': 'locache',
    'language': 'JavaScript'
})

locache.getMany(['name', 'language'])
// ['locache', 'JavaScript']

locache.removeMany(['name', 'language'])

Setting values that expire

seconds = 5;
locache.set("key", "value", seconds);

// After 5 seconds this will return null.
locache.get("key");

Incrementing and decrementing? Sure.

locache.incr("counter")
// 1
locache.incr("counter")
// 2
locache.decr("counter")
// 1
locache.decr("counter")
// 0
locache.decr("counter")
// -1

Flushing the cache

Use the following to clear only the locache values stored in localStorage.

locache.flush()

Performing cleanup

Since localStorage doesn't support expiring values, they will still be left around. This may or may not be a problem for you. If you want to make sure they are cleaned up, use the following method on page load, or with a setTimeout loop.

locache.cleanup()

locache's People

Contributors

d0ugal avatar elidupuis avatar jobedom avatar riophae avatar seriousm avatar sipmann avatar syntaxcoloring avatar wuchangming avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

locache's Issues

[enhancement] Add missing bower.json.

Hey, maintainer(s) of d0ugal/locache!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library d0ugal/locache is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "d0ugal/locache",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

flush()

is there a reason why the expire-keys aren't cleaned up while flushing?
it doesn't break anything, it just looks ugly...

Thanks

Support for sessionStorage

Hey, is there a reason you did not implement sessionStorage? I really like the expire feature but sometimes you just want to remove all storage or only some storage when the session ends.

Asynchronous API for locache

One of the problems that locache faces, is that DOM Storage (localStorage and sessionStorage) is a fully synchronous API. This means that access is blocking and can freeze the browser. This can happen if localStorge is being used from multiple tabs for example.

While I've not really experienced this problem myself in practice as the delay if any has been so small. However, a number of people have brought it up and its well documented if you were to search for it. Perhaps more benchmarks are needed.

Solution

At the moment, I've got a proof of concept that uses window.postMessage to create a defer system for the IO access. The code can be seen in my feature/async branch, or more specifically;

API

The biggest problem is coming up with an API that is both clear and easy to use. The ultimate goal is to add async, but keep an API as clear as we have now. This seems to be a common problem with async API's. Below is my current proposal, which is similar to what I have in the branch with a few tweaks.

// Set a key with a callback for when its done
locache.set("key", "value").finished(function(event){
    console.log("The write is finished")
})

// Get a key with a callback, that is passed an event
// object that contains the value
locache.get("key").finished(function(event){
    console.log("The read has returned " + event.data)
})

// Get an object, and wait for it to return.
var value = locache.get("key").wait()

// If you don't add anything, all you'll get is a deffered, 
// the operation will happen, but you wont get the 
// result - this is the worst bit, as one of the simplest
// API calls.
var deferred = locache.get("key")

Or, a slight alternative, that provides more hooks that can be chained. I'm not convinced this is all totally useful however. Is there value in having two callbacks for expired vs empty? or maybe there should only be one as above but then the event object is populated with some of this metadata.

locache.get("key").exists(function(event){
    console.log("They key was found with the value" + event.data)
}).expired(function(event){
    console.log("They key was found, but it had expired")
}).empty(function(event){
    console.log("They key was not found")
))

Future?

Ideally, something like WebWorkers would be great for this and its pretty much what they are designed for. However, there are two problems, firstly and most importantly, within a webworker while you can access a number of things, you can't access localStorage or sessionStorage. The second problem, that is less of an issue, is that IE doesn't support webworkers before version 9. So this idea has to be shelved, but something along these lines would be great.

IE6, IE7 maybe IE8

This plugin does not work on those versions of IE.

The first issue is that they do not support addEventListener, and require attachEvent to be used instead; after I modified my local copy to account for this I still go errors about this.async on line 37.

This needs looking at for compatibility with those versions of IE.

Error in flushing

First thanks for this nice lib, it was just what I was looking for.

There is a small bug in the flush method.

First you get the length in a local variable and use that for your loop,
in the loop you remove items and with that reduce the actual length,
after that it is possible for the line that gets the key to return an undefined because of the index being larger than the actual length.

I think line 266 should be: this.remove(key);

https://github.com/d0ugal-archive/locache/blob/83787513bb4ee5be38f3e8d870a9cb71187ce09a/locache.js#L266

line 266 should be:

this.remove(key); 

because line 308:

LocacheCache.prototype.remove = function (key) {

        // If the storage backend isn't enabled perform a no-op.
        if (!this.storage.enabled()) {
            return;
        }

        var expireKey = this.expirekey(key);
        var valueKey = this.key(key);

        this.storage.remove(expireKey);
        this.storage.remove(valueKey);

    };

https://github.com/d0ugal-archive/locache/blob/83787513bb4ee5be38f3e8d870a9cb71187ce09a/locache.js#L308

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.