Code Monkey home page Code Monkey logo

sticky's Introduction

Sticky

Sticky is a simple, key/value pair browser-storage cache leveraging the latest HTML5 storage API's.

Sticky persists in your preferred order to one of indexedDB, webSQL, localStorage, globalStorage, or cookies.

Features

  • Test coverage
  • Callbacks for everything
  • Multiple stores
  • Store strings, numbers, and objects – JSON in and JSON out
  • Simple abstraction for IndexedDB and WebSQL's complexity
  • MIT licensed

Storage Mechanisms and Browser Support

  • IndexedDB
    IE 10+, Firefox 4+ and Chrome 11+
  • WebSQL (SQLite)
    Chrome 4+, Opera 10.5+, Safari 3.1+ and Android Browser 2.1+ 5MB of data per DB, but can request more
  • localStorage
    Safari 4+, Mobile Safari (iPhone/iPad), Firefox 3.5+, Internet Explorer 8+ and Chrome 4+ 5MB of data per domain
  • globalStorage
    Firefox 2-3
  • Cookies
    Usually 4KB+ per domain.

For more compatibility information, see: caniuse.com.

Installation

bower install sticky-store

Getting Started

HTML:

<script src="sticky.js" type="text/javascript"></script>

JavaScript:

var store = new StickyStore();

store.set('color', 'red');
store.get('color');
store.remove('color');

Initialize

First, you must create the StickyStore like so:

var store = new StickyStore();

Alternatively, you can specify some options for this store by passing the options argument:

var store = new StickyStore({
    name: 'Sticky',
    adapters: ['localStorage', 'indexedDB', 'webSQL', 'cookie'],
    ready: function() {},
    expires: (24*60*60*1000),
    size: 5
});

Because indexedDB and webSQL operate asynchronously, Sticky will fire the ready event after all storage interfaces have been established.

Options

All settings are optional.

name String
The store name. You must specificy a store name to use multiple stores. Only alphanumeric characters are allowed.

adapters Array
An array of storage adapters to use, in preferred order. Defaults to ['localStorage', 'indexedDB', 'webSQL', 'cookie'].

ready Function
This function is called after the store has been initialized and at least one storage interface has been connected.

expires Number
Cookie expiration in milliseconds.

size Number
webSQL database size in megabytes.

get()

Retrieves a stored item.

If the preferred available adapter is asynchronous, you must use callbacks as StickyStore.get() will not return a value.

Parameters

key String/Array Key or array of keys callback The callback's first argument's value will be the stored item or array of items, or false on failure. Mixed (Optional)
adapter The storage adapter to use. String (Optional)

Returns

Returns stored item or false.

Example
// Synchronous
var result = store.get('something');

// Asynchronous
store.get('something', function(result) {
    console.log(result);
});

set()

Stores an item and returns the stored item or false on failure. You can pass any type of value: string, array, object, and number.

Parameters

key String/Array Key or array of keys item Mixed/Array Item or array of items callback The callback's first argument's value will be the stored item or array of items, or false on failure. Mixed (Optional)

adapter The adapter to use. String (Optional)

Returns

Returns stored item or false.

Example

You can set strings or numbers:

store.set('color', 'red');
store.set('version', 5);

Or objects:

store.set('car', {
    make: 'Volkswagen',
    model: 'Golf GTI',
    year: 2001
});

You can also specify a callback:

store.set('color', 'red', function(result) {
    console.log(result); // Outputs "red"
});

remove()

Removes the cached value and returns true if successful.

Parameters

key Key String
callback Callback's argument is true for success and false for failure. Mixed (Optional)
adapter The adapter to use. String (Optional)

Returns

Returns true for success or false for failure.

Example
store.remove('something');

removeAll()

Removes all stored items from all storage mechanisms.

Parameters

callback Mixed (Optional)

Example
store.removeAll();

Events

Sticky has events for errors, get, set, and remove.

Ready

store.on('ready', function(store) {
    console.log(store); // Returns the ready store object
});

Get

store.on('get', function(key, result) {
    console.log(key); // Returns key of item retrieved
    console.log(result); // Returns value of item retrieved
});

Set

store.on('set', function(key, result) {
    console.log(key); // Returns key of the item set
    console.log(result); // Returns value of item set
});

Remove

store.on('remove', function(key) {
    console.log(key); // Returns key of the item removed
});

Error

store.on('error', function(error, item) {
    console.log(error); // Returns the error message
    console.log(item); // Returns the item, if available
});

License

Copyright 2011 Alexander C. Mingoia

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

sticky's People

Contributors

alexmingoia avatar chris-morgan avatar honi avatar idev247 avatar jkaflik avatar julien-duponchelle avatar peppelorum avatar reyesr 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

sticky's Issues

Defining adapters causes error...

I'm working on trying to use sticky for a project and I've got a bit of code I've written to generate dummy data...

You can see all of my code here: http://pastebin.com/sSnTH5PH

Anyway, This bit appears to be the offending piece when I initialize Stickystore...

var store = new StickyStore({
adapters: ['webSQL', 'indexedDB', 'localStorage'],
ready:function(){
console.log("Database loaded");
},
size:200
});

If I remove the adapters option - it runs fine. If I keep the adapters option - I get the following error in Chrome:

Uncaught TypeError: Cannot read property 'index' of undefined

StickyStore.exec/html5/js/sticky-2.8.js:181
StickyStore.set/html5/js/sticky-2.8.js:292
GetMyJSONbuildjson.js:84
(anonymous function)/html5/#:645
f.Callbacks.njquery-1.7.1.min.js:2
f.Callbacks.o.fireWithjquery-1.7.1.min.js:2
e.extend.readyjquery-1.7.1.min.js:2
c.addEventListener.Bjquery-1.7.1.min.js:2
/html5/#:620

Any ideas?

IndexedDB without serialization

From what I've read it sounds like IndexedDB can store most JS objects directly without needing to serialize... have you considered supporting this?

Error on FireFox10

Sticky now doesn't work on the new FireFox 10.

The error info "This error occurred because an operation was not allowed on an object. A retry of the same operation would fail unless the cause of the error is corrected."

http://www.mozilla.org/en-US/firefox/10.0/releasenotes/
In release notes they mentioned "We've added IndexedDB APIs to more closely match the specification".Looks like the FF team updated the IndexedDB API on FF 10.

https://dvcs.w3.org/hg/IndexedDB/raw-file/3ac0182139b3/Speclet_020_IDB_API_Constructs.html

StickyStore.get should support a 'default' argument

It would be nice if StickStore.get supported an extra 'default' argument.

At present:

var foo = store.get('foo');
if (foo === null) {
    foo = 'bar';
}

This would be nicer done as:

var foo = store.get('foo', 'bar')

Then, if the key foo doesn't exist, it'll return the value 'bar'.

(Python's dict.get does this. Basically, it's basically def get(self, key, default=None).)

Rationale: It's very useful for configuration stores as this will probably be used a lot for as it means that you don't need to worry about whether an option is set but can take a default value immediately and easily.

tests?

It'd be great to have tests for this, so we can confirm all the various adapters are working as expected.

Cheers

indexeddb future compat

IE10 uses msIndexedDB in ie10pp4. you can betatest it on browserstack
Opera is maybe implementing it.

so you might want to add those prefixes in

Different users and init

I have built a workaround for an exception that we are getting when I login with an invalid user then a valid user. The code is at about line 438 in sticky.js:

    request.onsuccess = function (event) {
        if (event.target.result &&
            (!store.adapters.indexedDB.io ||
              store.adapters.indexedDB.io.name !== ((event.target.result.db) ? event.target.result.db.name : event.target.result.name))) {
            // FF is event.target.result, Chrome is event.target.result.db
            store.adapters.indexedDB.io = (event.target.result.db) ? event.target.result.db : event.target.result
        }
        // Backwards compatibility for older indexedDB implementations before
        // IDBDatabase.setVersion() was removed.

As opposed to

    request.onsuccess = function (event) {
        // FF is event.target.result, Chrome is event.target.result.db
        if (!store.adapters.indexedDB.io && event.target.result) {
            store.adapters.indexedDB.io = (event.target.result.db) ? event.target.result.db : event.target.result
        }
        // Backwards compatibility for older indexedDB implementations before
        // IDBDatabase.setVersion() was removed.

Comments?

Kevin

数据同步

目前只是方便浏览器存储,如果能方便的进行与服务器同步就非常好了!

Performance of memory cache

I got an email alerting me to a performance problem with large data sets. Sticky persists everything to memory, which is partly because it's an easy way of providing synchronous functionality for webSQL/indexedDB's asynchronous methods.

Ideally, there is no need for a memory cache. Sticky should avoid it and use setTimeout trickery to retain synchronous functionality.

Performance Comparison...

So 'Sticky' is EXACTLY what I've been looking for. I've been searching for something like this for ages...

I've wanted to build an HTML5 app but needed a way to abstract the storage situation - but I'm looking to deal with a high volume of data (50,000 - 100,000 records or more). I know WebSQL could handle it - but I'm not so sure about IndexedDB, LocalStorage, or GlobalStorage (certainly not cookies).

I ran a test and was able to get 20,000 records to store... but sometimes it seems hard to tell which storage method is active in Chrome and firefox doesn't seem to have a way to let you peek into the datastore.

One other thing I found was that removeall did seem to fail in chrome (despite a callback of true)... so I'm not sure what I was doing wrong.

I think there's a question in here somewhere... but I think it'd be nice to see just how hard we can push these data storage methods...

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.