local-storage - 是否有在 SPA(html5 单页应用程序)中同步本地和远程数据的最佳实践/模式?

标签 local-storage data-synchronization singlepage single-page-application breeze

我正在用 jqueryMobile + 淘汰赛 + Breeze + WebAPI 编写一个简单的“todo - helloworld”
了解移动环境中的 SPA(单页应用程序)(不可靠的互联网连接)

为了启用离线使用,WebApp 将利用

  • 应用缓存
  • 本地存储

  • 该应用程序应尽可能使用远程数据库来加载和保存数据,但应能够在离线时无缝切换到本地存储,并在重新上线时同步本地/远程更改。

    现在回到问题:
    该应用程序将使用 Breeze 的 EntityManager 来管理数据(本地缓存和远程同步)
  • “远程数据库”

  • 为了减轻不一致/并发问题,我将使用 2 个本地存储键:
  • “localDb”用于远程数据库的本地副本(待办事项列表)
  • 应用程序无法提交到远程数据库的更改的“localPendingChanges”

  • 所以流程或多或少是(伪代码):
    LoadData
      if(online)
        load remoteDb
        save localDb                   // save a local copy of the fresh loaded remotDb
        if(localPendingChanges)
          load localPendingChanges     // we are merging in the Breeze entityManager remote data with localPendingChanges
          Savedata                     // we are online and we have pending changes, so we should sync everything back to the remoteDb as soon as possible
      if(offline)
        load localDb
        if(localPendingChanges)
          load localPendingChanges     // we are merging in the Breeze entityManager local data with localPendingChanges
    
    SaveData
      if(online)
        save remoteDb
        clear localPendingChanges      // until we are online there is no need to keep localPendingChanges
        LoadData                       // we are loading data from remoteDb to update our localDb to the latest version
      if(offline)
        save localPendingChanges       // we are saving only the changes to localstorage
    

    您如何看待这种方法?这是一团糟吗?可以吗?
    多用户场景中的并发问题呢?

    最佳答案

    这似乎是合理的,不太确定为什么要使用两个 localStorage 键。放置在 localStorage 中的每个实体的 entityState(未修改、修改、添加、删除)都得到维护,因此您始终可以从任何本地副本中“提取”(请参阅​​ EntityManager.getEntities 方法)仅挂起的更改。那么为什么不在关闭应用程序之前将整个 entityManager 状态保存到 localStorage 。

    至于并发问题,你绝对应该为每个 entityType 设置一个并发属性。只要它存在,并且如果您通过 Entity Framework 进行保存, Breeze 将在保存期间检测到任何乐观并发冲突并抛出异常。显然,您已经为您的应用程序确定了此类异常后的正确行为。

    我相信您已经看过它,但是 QueryOptions.MergeStrategy (PreserveChanges, OverwriteChanges) 在任何查询后保留或覆盖本地机器上的数据非常有用。

    关于local-storage - 是否有在 SPA(html5 单页应用程序)中同步本地和远程数据的最佳实践/模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13846456/

    相关文章:

    jquery - Google Analytics 和 jQuery fullpage.js

    local-storage - 使用 Chrome/Firefox devtools 检查其他站点的 LocalStorage

    reactjs - React - “localStorage is not defined” 错误显示

    ios - CTTelephonyNetworkInfo 的 currentRadioAccessTechnology 模棱两可的响应

    android sqlite 双向同步 sqlite

    javascript - 如何在 Backbone js中全局访问路由器?

    javascript - 如何使用javascript将数据保存到本地硬盘?

    javascript - LocalForage、图像和 Blob

    mysql - 在 mysql 中更新触发器后触发并将该数据插入 mongodb

    javascript - 停止导航以进行 ajax 调用