英文:
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 "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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论