query-state
Application state in query string.
https://anvaka.github.io/query-state/#?name=world
usage
Grab it from npm and use with your favorite bundler:
npm install query-state --save
Or download from CDN:
<script src='https://cdn.rawgit.com/anvaka/query-state/v4.0.0/dist/query-state.min.js'></script>
If you downloaded from CDN the library will be available under queryState
global name.
var qs = queryState();
var appState = qs.get();
qs.onChange(function(appState) {
console.log('app state changed!', appState);
});
qs.set('answer', 42);
console.log(window.location.hash.indexOf('answer=42'))
qs.set({
name: 'Haddaway',
song: 'What is love?'
});
defaults
If you want to initialize app state with default values, you can pass them into
query state function:
var qs = queryState({
answer: 42
});
type limitations
This is a very simple module that currently does not support nested objects.
I.e. you cannot set application state to {foo: {bar: 42}}
. If you need this
behavior, most likely this module is not for you.
We do support primitive types serialization/deserialization:
Sharing between modules (singleton)
If you are using a bundler (e.g. browserify or webpack), its often desirable
to have just one instance of the application state, shared between files. Normally
this is accomplished via singleton pattern. The library exposes singleton
instance for your convenience:
var stateInFileA = queryState.instance();
var stateInFileB = queryState.instance();
NOTE: This is "lazy" implementation of the singleton: The instance is not created
until you call queryState.instance()
. After initial call the return value is
always the same.
Defaults in singleton scenario
Each of your module may desire to pass its own defaults. You can do it by passing
optional defaults
object:
var stateInFileA = queryState.instance({name: 'John'});
var stateInFileB = queryState.instance({age: 42});
var stateInfileC = queryState.instance({age: 100, height: 180})
search instead of hash
By default query-state
saves state in the hash
part of the url. But what if
we want to store state in the search
part instead?
Instead of awesome-site.com/#?answer=42 we want awesome-site.com/?answer=42.
Pass an optional argument to tell query-state use the search part:
var qs = queryState({
answer: 42
}, {
useSearch: true
});
This can be especially useful if you are planning to share links on social media,
as hash part of the query string is not visible to the servers, and they often
consider two different links to be the same.
clean up
Normally your app state will live as long as your application. However if you
do need to clean up resources (e.g. unloading your app) you can call qs.dispose()
var qs = queryState();
qs.dispose();
license
MIT