depot

2018-08-08 admin

depot是什么

什么是depot,depot.js is a namespaced localStorage wrapper with a simple API.

depot介绍、depot使用

depot.js

build status

depot.js

Description

depot.js is a namespaced localStorage wrapper with a simple API. There are other tools out there but none of them had what I was looking for.

Setup

You can install depot.js via npm:

  npm install depotjs --save

or load it directly via <script src="depot.browser.js"></script>. The dist folder contains the most recent minified browser version depot.browser.js.

Dependencies

depot.js does not depend on any other libraries however if you plan to support older browsers you will need to include ES5-shim.

If you plan to run it on browsers that don’t support localStorage you may try to include storage polyfill.

API

  • save(record)

  • saveAll(array)

  • updateAll(hash)

  • update(hash)

  • find(hash | function)

  • all()

  • destroy(id | record)

  • destroyAll(none | hash | function)

  • get(id)

  • size()

Usage

Import depot

import depot from 'depotjs';

Define new store

const todos = depot('todos');

Add new records

_id property will be generated as GUID and attached to each new record:

todos.save({ title: "todo1" });
todos.save({ title: "todo2", completed: true });
todos.save({ title: "todo3", completed: true });

Add multiple records at once

todos.saveAll([ { title: "todo1" }, { title: "todo2" }, { title: "todo3" } ]);

Update all records

todos.updateAll({ completed: false });

Return all records

todos.all(); // [{ _id: 1, title "todo1" }, { _id: 2, title: todo2 }]

Find records

  • find based on given criteria
todos.find({ completed: true }); // [{ _id: 2, title: "todo2" }, { _id: 3, title: "todo3" }]
  • find based on given function
todos.find(record => record.completed && record.title == "todo3"); // [{ _id: 3, title: "todo3" }]

Return single record by id

todos.get(1); // { _id: 1, title: "todo1" }

Destroy single record

Destroy all records

  • destroy by given criteria
todos.destroyAll({ completed: true });
  • destroy by given function
todos.destroyAll(record => record.completed && record.title === "todo3");

Options

You can pass a second parameter to depot with additional options.

const todos = depot("todos", options);

Available options:

  • idAttribute - used to override record id property (default: _id)
const todos = depot("todos", { idAttribute: 'id' });
  • storageAdaptor - used to override storage type (default: localStorage)
const todos = depot('todos', { storageAdaptor: sessionStorage });

Contributors:

License:

<pre>The MIT License </pre>

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-37547.html

文章标题:depot

回到顶部