当前位置: 首页 > 工具软件 > KV.JS > 使用案例 >

基恩士kv模块_内置Web模块:如何使用KV存储

岳卓君
2023-12-01

基恩士kv模块

The release of KV Storage is a big deal for the web platform. It’s part of the Standard Library Proposal which could see a more extensive standard library being introduced for JavaScript.

KV Storage的发布对于Web平台来说意义重大。 它是标准库提案的一部分,可以看到针对JavaScript引入了更广泛的标准库。

Before jumping in to what kv-storage is, let’s first discuss how we can store data within the browser. If I wanted to store some local data right now, one of my main options would be the use of localStorage.

在介绍什么是 kv-storage之前,让我们首先讨论如何在浏览器中存储数据。 如果我现在想存储一些本地数据,我的主要选择之一就是使用localStorage

With that in mind, let’s create a simple Todo application with JavaScript that takes advantage of localStorage. We’ll need two files - index.html and main.js:

考虑到这一点,让我们使用JavaScript创建一个简单的Todo应用程序,该应用程序利用localStorage优势。 我们需要两个文件- index.htmlmain.js

main.js
main.js
const TODOS_KEY = 'todos';
const ul = document.getElementsByTagName('ul')[0];

const showExistingTodos = todos => {
  if (todos.length > 0) {
    todos.map(todo => {
      addLi(todo);
    });
  }
};

const addTodo = () => {
  const input = document.getElementById('todoInput').value;

  if (input.length > 0) {
    addLi(input);
    saveTodo(input);

    document.getElementById('todoInput').value = '';
  }
};

const addLi = text => {
  const li = document.createElement('li');

  li.appendChild(document.createTextNode(text));

  ul.appendChild(li);
};

const saveTodo = todo => {
  let loadedTodos = loadTodos();

  loadedTodos = [...loadedTodos, todo];

  localStorage.setItem(TODOS_KEY, JSON.stringify(loadedTodos));
};

const loadTodos = () => {
  const todos = JSON.parse(localStorage.getItem(TODOS_KEY));

  return todos != null ? todos : [];
};

const clearTodos = () => {
  localStorage.removeItem(TODOS_KEY);

  const todos = Array.from(document.getElementsByTagName('li'));

  todos.map(todo => ul.removeChild(todo));
};

const todos = loadTodos();

showExistingTodos(todos);
index.html
index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <input id="todoInput" type="text" />  
    <button onclick="addTodo()">Add Todo</button>
    <button onclick="clearTodos()">Clear todos</button>
  </div>

  <ul>

  </ul>

  <script src="main.js"></script>
</body>
</html>

While this could definitely be improved, we now have an application that we can use as an example. If we try and add some Todo items and then refresh the page, we’ll see that they appear instantly!

尽管可以肯定地改进了它,但是我们现在有一个可以用作示例的应用程序。 如果我们尝试添加一些待办事项,然后刷新页面,我们会发现它们会立即显示!

Hmm… I did some research and found out that localStorage is synchronous. What does that mean for our application?

嗯……我做了一些研究,发现localStorage是同步的。 这对我们的应用意味着什么?

Essentially, this means that calls to localStorage will block rendering inside of the DOM. This may may represent a problem if we had lots of elements in localStorage and will significantly impact performance.

本质上,这意味着对localStorage调用将阻止DOM内部的呈现。 如果我们在localStorage有很多元素,这可能表示一个问题,并且会显着影响性能。

Let’s take a look at an experimental built-in module named KV storage (for key/value storage). This is built on IndexedDB, an asynchronous storage API.

让我们看一下名为KV存储(用于键/值存储)的实验性内置模块。 这是基于IndexedDB(异步存储API)构建的。

Why not use IndexedDB natively then?

那为什么不本地使用IndexedDB呢?

The use of KV storage gives us a more intuitive API that is similar to localStorage. We also don’t need to turn to a third party IndexedDB library, we can now use this directly from within the browser!

KV存储的使用为我们提供了一个更直观的API,类似于localStorage 。 我们也不需要转向第三方IndexedDB库,现在我们可以直接在浏览器中使用它了!

KV存储 (KV Storage)

For this example we’ll need to enable Experimental Features within Chrome. Inside of your Chrome browser, navigate to the following address:

对于此示例,我们需要在Chrome中启用实验性功能。 在您的Chrome浏览器中,导航至以下地址:

Select “Enabled” on Experimental Web Platform features: [chrome://flags/#enable-experimental-web-platform-features](chrome://flags/#enable-experimental-web-platform-features).

在“实验Web平台”功能上选择“启用”:[chrome:// flags /#enable-experimental-web-platform-features](chrome:// flags /#enable-experimental-web-platform-features)。

It’s also a good idea to use Chrome Canary for any and all experimental/new Web features. I’ll be using it for our example.

Chrome Canary用于所有和所有实验性/新的Web功能也是一个好主意。 我将在我们的示例中使用它。

We’ll now need to perform the following updates:

现在,我们需要执行以下更新:

Inside of index.html, import main.js as a module:

index.html内部,将main.js导入为模块:

<script type="module" src="main.js"></script>

Next, we can update our saveTodo function to use storage.set() instead of localStorage.setItem()

接下来,我们可以更新saveTodo函数以使用storage.set()而不是localStorage.setItem()

const saveTodo = async todo => {
  let loadedTodos = await loadTodos();

  loadedTodos = [...loadedTodos, todo];

  await storage.set(TODOS_KEY, loadedTodos);
};

Our loadTodos function uses storage.get() instead of localStorage.getItem():

我们的loadTodos函数使用storage.get()而不是localStorage.getItem()

const loadTodos = async () => {
  const todos = await storage.get(TODOS_KEY);

  return todos != null ? todos : [];
};

Notice here how we’re dealing with the asynchronicity with ease using async/await functions.

注意这里我们如何使用async / await函数轻松地处理异步性。



Finally, we can improve our clearTodos function by using storage.delete() instead of localStorage.removeItem():

最后,我们可以使用storage.delete()而不是localStorage.removeItem()来改进clearTodos函数:

const clearTodos = () => {
  storage.delete(TODOS_KEY);

  const todos = Array.from(document.getElementsByTagName('li'));

  todos.map(todo => ul.removeChild(todo));
};

We’ll also need to expose these to the window object:

我们还需要将这些暴露给window对象:

window.addTodo = addTodo;
window.clearTodos = clearTodos;

Our application now works once again, but instead of localStorage it uses the std:kv-storage built-in Web module. The best thing about this? It uses IndexedDB under the hood!

我们的应用程序现在可以再次运行, 但是它使用了内置的std:kv-storage Web模块来代替localStorage 。 最好的事情是什么? 它在后台使用IndexedDB!

This means everything is asynchronous (as referenced by our async and await promise calls, too).

这意味着一切都是异步的(也被我们的asyncawait promise调用所引用)。

客户支持 (Client support)

What if the browser doesn’t support kv-storage? At the moment, this is extremely likely. Luckily, there’s a polyfill available here: https://github.com/GoogleChromeLabs/kv-storage-polyfill.

如果浏览器不支持kv-storage怎么办? 目前,这极有可能发生。 幸运的是,这里有一个polyfill: https : //github.com/GoogleChromeLabs/kv-storage-polyfill

I’d recommend you add this to your application if you plan on using kv-storage in production at this stage.

如果您计划在此阶段在生产中使用kv-storage ,建议您将其添加到应用程序中。

进一步阅读 (Further reading)

Google has prepared a demo on kv-storage that you may find interesting to read. Here’s the URL: https://rollup-built-in-modules.glitch.me/

Google已准备了一个有关kv-storage的演示,您可能会觉得有趣。 这是URL: https : //rollup-built-in-modules.glitch.me/

翻译自: https://www.digitalocean.com/community/tutorials/js-kv-storage

基恩士kv模块

 类似资料: