如何跟踪 indexedDB 中的更改?

huangapple go评论60阅读模式
英文:

How to track changes in indexedDb?

问题

我继续搜索,听说 IndexedDb 没有观察者。那么如何跟踪数值的变化呢?这完全不可能吗?我目前正在使用 idb-keyval 来操作 IndexedDb。你有什么解决方案吗?或者我应该考虑使用类似 localforage 这样的库?

英文:

I continued to search, and I heard that IndexedDb does not have an observer. So how can I track the change value? Is it impossible at all? I am currently using IndexedDb using idb-keyval. Do you have any solution? Or should I use a library like localforage instead?

答案1

得分: 1

唯一的方法是使用中间函数或将代码注入到库中,或者修补 IndexedDB 本身。

使用中间代码的版本是最优的:

import { get, set } from "idb-keyval"

const bus = new EventBus<{
  'change:counter': number
}>()
const cast = new BroadcastChannel('watcher-indexeddb')

function mget(name: string): Promise<any> {
  return get(name)
}
async function mset(name: string, value: any): Promise<void> {
  await set(name, value)
  bus.emit(`change:${name}`, value)
  cast.postMessage({ type: `change:${name}`, value })
}

cast.addEventListener("message", event => {
  if (event.data?.type?.startsWith("change"))
    bus.emit(event.data.type, event.data.value)
})

bus.on("change:counter", value => {
  console.log("Counter changed to %s", value)
})

// Usage: mset('counter', 12)
英文:

The only way is to use intermediate functions or inject code into the library or patch IndexedDB itself

A version using intermediate code is the most optimal:

import { get, set } from &quot;idb-keyval&quot;

const bus = new EventBus&lt;{
  &#39;change:counter&#39;: number
}&gt;()
const cast = new BroadcastChannel(&#39;watcher-indexeddb&#39;)

function mget(name: string): Promise&lt;any&gt; {
  return get(name)
}
async function mset(name: string, value: any): Promise&lt;void&gt; {
  await set(name, value)
  bus.emit(`change:${name}`, value)
  cast.postMessage({ type: `change:${name}`, value })
}

cast.addEventListener(&quot;message&quot;, event =&gt; {
  if (event.data?.type?.startsWith(&quot;change&quot;))
    bus.emit(event.data.type, event.data.value)
})

bus.on(&quot;change:counter&quot;, value =&gt; {
  console.log(&quot;Counter changed to %s&quot;, value)
})

// Usage: mset(&#39;counter&#39;, 12)

huangapple
  • 本文由 发表于 2023年7月14日 00:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定