Giter Site home page Giter Site logo

lockr's People

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  avatar  avatar  avatar  avatar  avatar  avatar

lockr's Issues

Refactor specs

Examples in the specs are tightly coupled between them and also they must run in a predefined sequence, which makes them harder to read, follow and write.

We should find an elegant way to flush localStorage before each example and a way to support factories.

How can I get by a key from array

Let's stay with official examples:
Lockr.set('users', [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]);

and after Lockr.get('users'); it give me sting (JSON)?

But how can I make an "each" loop to get all key/value?

Something like this but this give me en error
$.each(Lockr.get('selects'), function (index, value) { console.log(value); });

how to remove an object from collection

I added my product into shopping cart by using:

Lockr.sadd("cart", {id: 123, name: abc});
Lockr.sadd("cart", {id: 456, name: def});

How to remove a particular object from cart? e.g I later want to remove the first object {id: 123, name: abc}

thanks

sessionStorage support

I'd like to use lockr for a new component, but with sessionStorage instead of localStorage.
As far as I can see lockr is built for localStorage only.

Would it be possible to provide sessionStorage support as well or is this plugin intentionally restricted to localStorage?

Get values of objects

When I try to do Lockr.get('obj'); and obj holds an array of objects, I jut get [object object] and not the actual value of these objects. When I use JSON.stringify(obj) I get the values.
This is not what I expected after reading the documentation of Lockr.

TypeError: Lockr.get(...) is undefined

I have here a very simple code which is roughly like this:

object.somedata: {
'a': Lockr.get('a'),
'b': Lockr.get('b'),
'c': Lockr.get('c')
}

At the row "c" I get now the error message "TypeError: Lockr.get(...) is undefined" in the console of Firefox. Any idea why?

Can't store functions inside objects

Hello.Consider the following foo object with a name property and a greet function:

var foo = {name:"foo",greet:function(){console.log("Hello:"+this.name)}

Now we store it:
Lockr.set("test",foo)
Let's try to restore it :
var restored = Lockr.get("test")
If we try to do restored.greet() we get an error saying restored.greet is not a function.
Why is this happening?

Lockr.sismember - unused variable query_key

Lockr.sismember = function(key, value, options) {
    -----> var query_key = this._getPrefixedKey(key, options); <----

    return Lockr.smembers(key).indexOf(value) > -1;
  };

Please, remove it, if it is not required.

Add append functionality

Please add append functionality.
ex:-
Lockr.append( key, value);

check first key exist in storage. if not then create new on. if exist then append in existing value.

getLastKey and getFirstKey function add

Please add getLastKey and getFirstKey;

Lockr.getLast = function(){
    return Object.keys(localStorage)[Object.keys(localStorage).length - 1];
}
Lockr.getFirst = function(){
    return Object.keys(localStorage)[0];
}

Web developers will be need first, last key ot findKey function for find something.

Should Lockr flush items added to the localStorage with setItem method.

Let's say we do the following to store a name in localStorage using Lockr:
Lockr.set("name","foo");
Now let's add an item to the localStorage without using Lockr"
localStorage.setItem("fakeName","just a fake name");
As you can see fakeName item was added to localStorage without using Lockr.
So now comes the question.
Should Lockr clear all the localStorage when .flush() is called or only the items added by Lockr?

Lockr.rm method

Hi,
I think the Lockr.rm method should look like this to correctly handle usage with prefix

  Lockr.rm =  function (key, options) {
    localStorage.removeItem(this._getPrefixedKey(key, options));
  }

Difference between get and getItem

Hi,

Thank you for writing this library. Its very helpful in my project.

Can you give some information on the difference between get and getItem. I'm asking because, for some reason, getItem is not working for me (Lockr.getItem(...) - getItem() is not a function)).

Regards,
Akash

Save Set() with Lockr

Hello.I have been trying to save the following to localStorage:

var a = new Set(); a.add(1); a.add(2);

Lockr.set('demo',a);
However if I do this :Lockr.get("demo") I get an empty object,Any ideas?

es6 import modules support

Recently switching my projects to es6 with babel, I'd like to do something like this with lockr:

import {
    get,
    set,
} from 'lockr'

but when I call get this error throws:

TypeError: Cannot read property '_getPrefixedKey' of undefined
var query_key = this._getPrefixedKey(key, options)

Not a big deal; importing the entire library is not a problem because it's small and minimal.

Thank you =]

Possible to import Lockr as non-global?

I've come across a situation where I need to use Lockr in two different places with different prefixes. But Locker.prefix = 'new_prefix_' will just override the old one. Is this possible at all?

Thanks for this amazing library!

Retrieving value which are not set by Lockr

Thanks for this super tiny package that elegantly handles the localStorage ๐Ÿ™‚

I can see that Lockr is not designed to retrieve data that are not set by itself. Can we make it to retreive the data that are not set by Lockr with the help of options argument ?

like,

window.localStorage.setItem('nameObj', JSON.stringify({first: 'Gokul', last: 'Kathirvel'}));

Lockr.get('nameObj');
// undefined

Lockr.get('nameObj', null, { processRaw: true });
// {first: 'Gokul', last: 'Kathirvel'}

or if the fetched value from storage is not abiding the structure (.data), then we can return the actual fetched value itself like this

storing FALSE using Lockr doesn't work as expected

Lockr.set("xyz", false); console.log(Lockr.get("xyz"));

the following prints "undefined" instead of the expected "false". looking at your code the problems seems to be somewhere here: https://github.com/tsironis/lockr/blob/master/lockr.js#L81 - your minifier changes that line to return null===value?missing:value.data||missing (https://github.com/tsironis/lockr/blob/master/lockr.min.js), which is a lot cleaner in my opinion and also quite obviously displays the problem at hand.

is this behavior by design?

Expire Local Storage.

Hello,
First of all, great package for maintaining Local storage. The thing which i have to ask here that how can i set a time/days to expire/clear local storage because i need to expire my shopping cart after 30 days or less if there is no working on it. Right now, i think there is no way to expire.

Thank you for any help.

Releasing v1.0

I think it's time to start planning our v1.0 release and a basic roadmap of how to get there.

I would like to get the discussion started on how we can improve this library. Any suggestions will be much appreciated.

Accessing data retrieved from Lockr.get();

Hi, so I am trying to utilize Lockr to enable a more advanced data storage system within my website. The problem is I'm not sure how to access the data once I've stored it in a more advanced way using Lockr. My code is below. I'm talking about specifically writing the data in a paragraph within the updateAllDataDisplay function when the page loads. I can get the data logged to the console, but I can't seem to manipulate it properly beyond that. My goal is to have the website display the entry date, entry time, exercise entry, food entry, and mood entry, in that order on the page. Any help? Thanks

// Script

// Goals: Be able to store data with the date, and a journal entry
    // Create dynamic showing of entries
// Be able to have multiple entries for one date in order
// Add food entries
// Add exercise entries
// Add weight entry add weight graph
// Add calorie entry
// Add mood entries for each date
// Add streak showings for entries
// Add calandar functionality
// 


(function(root, factory) {

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = factory(root, exports);
    }
  } else if (typeof define === 'function' && define.amd) {
    define(['exports'], function(exports) {
      root.Lockr = factory(root, exports);
    });
  } else {
    root.Lockr = factory(root, {});
  }

}(this, function(root, Lockr) {
  'use strict';

  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/)
    {
      var len = this.length >>> 0;

      var from = Number(arguments[1]) || 0;
      from = (from < 0)
      ? Math.ceil(from)
      : Math.floor(from);
      if (from < 0)
        from += len;

      for (; from < len; from++)
      {
        if (from in this &&
            this[from] === elt)
          return from;
      }
      return -1;
    };
  }

  Lockr.prefix = "";

  Lockr._getPrefixedKey = function(key, options) {
    options = options || {};

    if (options.noPrefix) {
      return key;
    } else {
      return this.prefix + key;
    }

  };

  Lockr.set = function (key, value, options) {
    var query_key = this._getPrefixedKey(key, options);

    try {
      localStorage.setItem(query_key, JSON.stringify({"data": value}));
    } catch (e) {
      if (console) console.warn("Lockr didn't successfully save the '{"+ key +": "+ value +"}' pair, because the localStorage is full.");
    }
  };

  Lockr.get = function (key, missing, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
            if(localStorage[query_key]) {
              value = {data: localStorage.getItem(query_key)};
            } else{
                value = null;
            }
    }
    
    if(!value) {
      return missing;
    }
    else if (typeof value === 'object' && typeof value.data !== 'undefined') {
      return value.data;
    }
  };

  Lockr.sadd = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json;

    var values = Lockr.smembers(key);

    if (values.indexOf(value) > -1) {
      return null;
    }

    try {
      values.push(value);
      json = JSON.stringify({"data": values});
      localStorage.setItem(query_key, json);
    } catch (e) {
      console.log(e);
      if (console) console.warn("Lockr didn't successfully add the "+ value +" to "+ key +" set, because the localStorage is full.");
    }
  };

  Lockr.smembers = function(key, options) {
    var query_key = this._getPrefixedKey(key, options),
        value;

    try {
      value = JSON.parse(localStorage.getItem(query_key));
    } catch (e) {
      value = null;
    }
    
    return (value && value.data) ? value.data : [];
  };

  Lockr.sismember = function(key, value, options) {
    return Lockr.smembers(key).indexOf(value) > -1;
  };

  Lockr.keys = function() {
    var keys = [];
    var allKeys = Object.keys(localStorage);

    if (Lockr.prefix.length === 0) {
      return allKeys;
    }

    allKeys.forEach(function (key) {
      if (key.indexOf(Lockr.prefix) !== -1) {
        keys.push(key.replace(Lockr.prefix, ''));
      }
    });

    return keys;
  };

  Lockr.getAll = function (includeKeys) {
    var keys = Lockr.keys();

    if (includeKeys) {
      return keys.reduce(function (accum, key) {
        var tempObj = {};
        tempObj[key] = Lockr.get(key);
        accum.push(tempObj);
        return accum;
      }, []);
    }

    return keys.map(function (key) {
      return Lockr.get(key);
    });
  };

  Lockr.srem = function(key, value, options) {
    var query_key = this._getPrefixedKey(key, options),
        json,
        index;

    var values = Lockr.smembers(key, value);

    index = values.indexOf(value);

    if (index > -1)
      values.splice(index, 1);

    json = JSON.stringify({"data": values});

    try {
      localStorage.setItem(query_key, json);
    } catch (e) {
      if (console) console.warn("Lockr couldn't remove the "+ value +" from the set "+ key);
    }
  };

  Lockr.rm =  function (key) {
    var queryKey = this._getPrefixedKey(key);
    
    localStorage.removeItem(queryKey);
  };

  Lockr.flush = function () {
    if (Lockr.prefix.length) {
      Lockr.keys().forEach(function(key) {
        localStorage.removeItem(Lockr._getPrefixedKey(key));
      });
    } else {
      localStorage.clear();
    }
  };
  return Lockr;

}));


//localStorage.removeItem('allData');
var allData = [];

init();

function init() {
    /*
    if (Lockr.get('allData') !== null && Lockr.get('allData') !== undefined) {
        allData = JSON.parse(Lockr.get("allData"));
        dataEntries = Lockr.get('dataEntries');
        //console.log(allData);
    } else {
        //console.log('blank exercise data array');
        allData = [];
        dataEntries = 0;
    }
    */
    if (Lockr.get('dataEntries') > 0) {
        dataEntries = Lockr.get('dataEntries');
    }
}

// Create exercise field
let a = document.createElement("input");
a.setAttribute("type", "text");
a.setAttribute("value", "How long did you exercise for today");
a.size = "40";
document.body.appendChild(a);

// Create two <br> between text fields
for (let i = 0; i < 2; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}


// Create diet text field
let e = document.createElement("input");
e.setAttribute("type", "text");
e.setAttribute("value", "What did you eat today");
e.size = "40";
document.body.appendChild(e);

// Create two <br> between text fields

for (let i = 0; i < 2; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}


let f = document.createElement("input");
f.setAttribute("type", "text");
f.setAttribute("value", "Describe your mood in detail today");
f.size = "40";
document.body.appendChild(f);

for (let i = 0; i < 2; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}

// Create save data button
let saveDataBtn = document.createElement("button");
saveDataBtn.innerHTML = "Save Data";   
document.body.appendChild(saveDataBtn);


for (let i = 0; i < 3; i ++) {
    let d = document.createElement('br');
    document.body.appendChild(d);
}

// Create clear data button
let clearDataBtn = document.createElement("button");
clearDataBtn.innerHTML = "Clear Data";   
document.body.appendChild(clearDataBtn);


// Create allData Header
let b = document.createElement("p");
let c = document.createTextNode('Saved Data:');
b.appendChild(c);
document.body.appendChild(b);


(function updateAllDataDisplay() {
    for (var i = 0; i < dataEntries; i++) {
        let currentEntry = Lockr.get(`data${i}`);
        console.log(currentEntry);
        let a = document.createElement("p");
        let b = document.createTextNode('blah');
        a.appendChild(b);
        document.body.appendChild(a);
    }
})();



/*
Goal: create buttons that toggle between showing a user inputted pragraph tracking their moood on the day they exercised for x number of inputted hours
*/

saveDataBtn.onclick = function () {
    var date = new Date();
    let day = date.getDate();
    let month = date.getMonth();
    let year = date.getFullYear();
    let hours = date.getHours();
    let mins = date.getMinutes();
    let secs = date.getSeconds();
    //allData.push(`${day}/${month + 1}/${year} (${hours}:${mins}:${secs}): ${a.value}. ${e.value}. ${f.value}.`);
    //localStorage.setItem("allData", JSON.stringify(allData));
    //Lockr.set('allData', JSON.stringify(allData));
    
    //Lockr.set('newData', [{first: `${a.value}`}, {second: `${e.value}`}, {third: `${f.value}`}]);
    //console.log(Lockr.get('newData'));
    
    dataEntries += 1;
    Lockr.set(`data${dataEntries}`, [{date:`${day}/${month + 1}/${year}`, time: `${hours}:${mins}:${secs}`, exerciseHours: a.value, food: e.value, mood: f.value}, {test: 'testing'}]);
    Lockr.set('dataEntries', dataEntries);
    console.log(Lockr.get(`data${dataEntries}`));
    console.log(dataEntries);
}

clearDataBtn.onclick = function () {
    //localStorage.removeItem('allData');
    for (var i = 0; i < dataEntries; i++) {
        Lockr.rm(`data${i}`);
    }
    dataEntries = 0;
    //Lockr.rm('');
}

ReferenceError: Lockr is not defined

Basic usage is causing a reference error. Thoughts?

  Lockr.prefix = 'lockr';
  Lockr.set('website', 'website.com');
  Lockr.set('categories', 8);
  Lockr.set('users', [{ name: 'John Doe', age: 18 }, { name: 'Jane Doe', age: 19 }]);

Bad prefix description

This code will not work.
You use prefix without underscore at the end. But in method getItem you use [prefix]_[key]. But underscore is never added to key, so correct would be localStorage.getItem('lockrusername');

Lockr.prefix = 'lockr';
Lockr.set('username', 'Coyote'); // Saved as string
localStorage.getItem('username');
> null
localStorage.getItem('lockr_username');
> {"data":123}

And you set username as string, but returned is number

Where condition

I'm using locker to manage a very large list of users.
I wonder how you do to perform a search.

Example result I expect
Lockr.set('users', [{name: 'John Doe', age: 18}, {name: 'Jane Doe', age: 19}]); Lockr.getWhere('users', {age = 18}]); // return {name: 'John Doe', age: 18}

Thanks

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.