jstorage - simple javascript plugin to store data locally

5
jStorage store data locally with JavaScript jStorage is a crossbrowser keyvalue store database to store data locally in the browser jStorage supports all major browsers, both in desktop (yes even Internet Explorer 6) and in mobile. Additionally jStorage is library agnostic, it works well with any other JavaScript library on the same webpage, be it jQuery, Prototype, MooTools or something else. Though you still need to have either a third party library (Prototype, MooTools) or JSON2 on the page to support older IE versions. jStorage supports storing Strings, Numbers, JavaScript objects, Arrays and even native XML nodes. jStorage also supports setting TTL values for auto expiring stored keys and best of all notifying other tabs/windows when a key has been changed or publishing/subscribing to events from the same or another tab/window, which makes jStorage also a local PubSub platform for web applications. jStorage is pretty small, about 7kB when minified and 4kB gzipped. Donate Support jStorage development Index 1. Basics 2. Download 3. Interactive test 4. Browser support 5. Usage 6. Function reference 7. Usage example 8. Issues 9. Contact and Copyright 1. Basics jStorage makes use of HTML5 local storage where available and userData behavior in Internet Explorer older versions. Current availability: jStorage supports all major browsers Internet Explorer 6+, Firefox 2+, Safari 4+, Chrome 4+, Opera 10.50+ If the browser doesn't support data caching, then no exceptions are raised jStorage can still be used by the script but nothing is actually stored. jStorage is really small, just about 7kB when minified (4kB when gzipped)!

Upload: rithuik1598

Post on 11-Nov-2015

219 views

Category:

Documents


3 download

DESCRIPTION

jstorage

TRANSCRIPT

  • 5/2/2015 jStoragesimpleJavaScriptplugintostoredatalocally

    http://www.jstorage.info/#basics 1/5

    jStoragestoredatalocallywithJavaScriptjStorageisacrossbrowserkeyvaluestoredatabasetostoredatalocallyinthebrowserjStoragesupportsallmajorbrowsers,bothindesktop(yesevenInternetExplorer6)andinmobile.

    AdditionallyjStorageislibraryagnostic,itworkswellwithanyotherJavaScriptlibraryonthesamewebpage,beitjQuery,Prototype,MooToolsorsomethingelse.Thoughyoustillneedtohaveeitherathirdpartylibrary(Prototype,MooTools)orJSON2onthepagetosupportolderIEversions.

    jStoragesupportsstoringStrings,Numbers,JavaScriptobjects,ArraysandevennativeXMLnodes.jStoragealsosupportssettingTTLvaluesforautoexpiringstoredkeysandbestofallnotifyingothertabs/windowswhenakeyhasbeenchangedorpublishing/subscribingtoeventsfromthesameoranothertab/window,whichmakesjStoragealsoalocalPubSubplatformforwebapplications.

    jStorageisprettysmall,about7kBwhenminifiedand4kBgzipped.

    Donate

    SupportjStoragedevelopment

    Index

    1. Basics2. Download3. Interactivetest4. Browsersupport5. Usage6. Functionreference7. Usageexample8. Issues9. ContactandCopyright

    1.Basics

    jStoragemakesuseofHTML5localstoragewhereavailableanduserDatabehaviorinInternetExplorerolderversions.

    Currentavailability:jStoragesupportsallmajorbrowsersInternetExplorer6+,Firefox2+,Safari4+,Chrome4+,Opera10.50+

    Ifthebrowserdoesn'tsupportdatacaching,thennoexceptionsareraisedjStoragecanstillbeusedbythescriptbutnothingisactuallystored.

    jStorageisreallysmall,justabout7kBwhenminified(4kBwhengzipped)!

  • 5/2/2015 jStoragesimpleJavaScriptplugintostoredatalocally

    http://www.jstorage.info/#basics 2/5

    2.Download

    jStoragecanbedownloadedatgithub(directdownloadlink)

    3.Interactivetest

    Addsomevaluesandrefreshthepageifyourbrowsersupportsstoringlocaldata,thenthevaluesshouldsurvivethepagerefresh.

    KEY VALUE

    ADD

    Clicking"GET"alertsthevalueforprovidedkeywiththemethod$.jStorage.get(key) GET

    Clearallsaveddata FLUSH

    4.Browsersupport

    Browser Storagesupport SurvivesbrowserrestartSurvivesbrowser

    crash Storagesize

    Chrome4 + + + 5MBFirefox3.6 + + + 5MBFirefox3 + + + 5MBFirefox2 + + + 5MBIE8 + + + 10MBIE7 + + + 128kBIE6 + + + 128kBOpera10.50 + + 5MBOpera10.10 N/A N/A N/ASafari4 + + + 5MBIphoneSafari + + + 5MBSafari3 N/A N/A N/A

    5.Usage

    jStoragerequiresPrototype,MooToolsorjQuery+jQueryJSONorJSON2.Eitherway,thesyntaxstaysthesame.

    SimplesetuptosupportjStoragewithJSON2

    /*$.jStorageisnowavailable*/

    SetupwithjQuery2

    /*$.jStorageisnowavailable*/

  • 5/2/2015 jStoragesimpleJavaScriptplugintostoredatalocally

    http://www.jstorage.info/#basics 3/5

    6.Functionreference

    set(key,value[,options])

    $.jStorage.set(key,value,options)

    Savesavaluetolocalstorage.keyneedstobestringotherwiseanexceptionisthrown.valuecanbeanyJSONeablevalue,includingobjectsandarraysoraXMLnode.CurrentlyXMLnodescan'tbenestedinsideotherobjects:$.jStorage.set("xml",xml_node)isOKbut$.jStorage.set("xml",{xml:xml_node})isnot.

    Optionsisanoptionaloptionsobject.Currentlyonlyavailableoptionisoptions.TTLwhichcanbeusedtosettheTTLvaluetothekey($.jStorage.set(key,value,{TTL:1000});).NBifnoTTLoptionvaluehasbeenset,anycurrentlyusedTTLvalueforthekeywillberemoved.

    get(key[,default])

    value=$.jStorage.get(key)value=$.jStorage.get(key,"defaultvalue")

    getretrievesthevalueifkeyexists,ordefaultifitdoesn't.keyneedstobestringotherwiseanexceptionisthrown.defaultcanbeanyvalue.

    deleteKey(key)

    $.jStorage.deleteKey(key)

    Removesakeyfromthestorage.keyneedstobestringotherwiseanexceptionisthrown.

    setTTL(key,ttl)

    $.jStorage.set("mykey","keyvalue");$.jStorage.setTTL("mykey",3000);//expiresin3seconds

    SetsaTTL(inmilliseconds)foranexistingkey.Use0ornegativevaluetoclearTTL.

    getTTL(key)

    ttl=$.jStorage.getTTL("mykey");//TTLinmillisecondsor0

    GetsremainingTTL(inmilliseconds)forakeyor0ifnotTTLhasbeenset.

    flush()

    $.jStorage.flush()

    Clearsthecache.

    index()

    $.jStorage.index()

    Returnsallthekeyscurrentlyinuseasanarray.varindex=$.jStorage.index();console.log(index);//["key1","key2","key3"]

    storageSize()

    $.jStorage.storageSize()

    Returnsthesizeofthestoreddatainbytes

    currentBackend()

  • 5/2/2015 jStoragesimpleJavaScriptplugintostoredatalocally

    http://www.jstorage.info/#basics 4/5

    $.jStorage.currentBackend()

    Returnsthestorageenginecurrentlyinuseorfalseifnone

    reInit()

    $.jStorage.reInit()

    Reloadsthedatafrombrowserstorage

    storageAvailable()

    $.jStorage.storageAvailable()

    Returnstrueifstorageisavailable

    subscribe(channel,callback)

    $.jStorage.subscribe("ch1",function(channel,payload){console.log(payload+"from"+channel);});

    SubscribestoaPublish/Subscribechannel)

    publish(channel,payload)

    $.jStorage.publish("ch1","data");

    PublishespayloadtoaPublish/Subscribechannel

    listenKeyChange(key,callback)

    $.jStorage.listenKeyChange("mykey",function(key,action){console.log(key+"hasbeen"+action);});

    Listensforupdatesforselectedkey.NB!evenupdatesmadeinotherwindows/tabsarereflected,sothisfeaturecanalsobeusedforsomekindofpublish/subscribeservice.

    stopListening(key[,callback])

    $.jStorage.stopListening("mykey");//cancelalllistenersfor"mykey"change

    Stopslisteningforkeychange.Ifcallbackisset,onlytheusedcallbackwillbecleared,otherwisealllistenerswillbedropped.

    7.Usageexample

    jQuery

    jQuerydoesn'tcomewithbuiltinJSONencoder/decodersoifyouneedtosupportIE6/IE7youshouldincludeoneyourseltlikeintheexample

    //Checkif"key"existsinthestoragevarvalue=$.jStorage.get("key");if(!value){//ifnotloadthedatafromtheservervalue=load_data_from_server()//andsaveit$.jStorage.set("key",value);

  • 5/2/2015 jStoragesimpleJavaScriptplugintostoredatalocally

    http://www.jstorage.info/#basics 5/5

    }

    Prototype

    //Checkif"key"existsinthestoragevarvalue=$.jStorage.get("key");if(!value){//ifnotloadthedatafromtheservervalue=load_data_from_server()//andsaveit$.jStorage.set("key",value);}

    8.Issues

    WhywouldyouwanttousejStoragewhencookiesworkalreadyineverybrowser?CookiesarenotmeanttosavelargequantitiesofdatalocallytheyaremeanttopassaroundIDvaluestokeeptrackofusers.InternetExplorerallowstouseupto20cookiesperdomainwiththepayloadof4kBpercookie.Itisn'tverymuch,especiallyconsideringtheneedtochunklargerdataintosmallerbits.Thefactthatthedata(max.80kB)issenttotheserverwith*every*calldoesn'tsoundmuchofagoodideaeither.

    9.ContactandCopyright

    20102012AndrisReinman,[email protected],sobasicallyyoucandowhateveryouwanttodowithit.