javascript - 如何在 ember 数据中缓存查询结果

标签 javascript jquery caching ember.js ember-data

我想在 ember-data 中缓存查询结果。 (查找查询)

明确一点:我不想缓存整个模型;只有什么模型是查询的结果。正确的位置在哪里?

我正在考虑在适配器中实现它并缓存 AJAX 调用的结果,但我认为这不是一个好的解决方案,因为我不想覆盖加载的、可能是更新的和/或修改的模型数据.

我认为只返回一个 ID 列表是不可能的,并且操作适配器这个简单用例的序列化程序似乎很困惑!

实际上我不希望为特定类型的查询调用findQuery。类似于 findAll 的行为。不错的东西类似于 queryShouldBeCached Hook 。

有好的解决方案吗?

最佳答案

我不是 Ember 专家,但我认为您可以使用纯 JS 解决方案来解决您的问题。

给定的 Ember 数据查询返回 promise ,例如return this.store.findAll('blog-post');//=> Promise,我们可以在具有高阶函数(返回函数的函数)的简单对象中缓存 promises。对象缓存可以替换为 localStoragesessionStorageMap 甚至 WeakMap 但我正在使用对象缓存使事情变得简单易懂。

您基本上要做的是替换以下调用:

return this.store.findAll('blog-post');

或多或少像:

return cachedStore.findAll('blog-post');

实际上,使用下面的解决方案可能看起来更像:

return cachedStore.call(this, 'findAll', 'blog-post');

因此,您将请求一次数据,并在后续调用中始终从缓存中返回。

让我向您展示实现的样子:

var cachedStore = (function () {
  // Your cache - in this case simple object literal
  var cache = {};

  // Actual method that will check cache for results before trying to query services
  return function (method) {
    var args = Array.prototype.slice.call(arguments, 1);
    var serializedArgs = JSON.stringify(args);

    if (!(serializedArgs in cache)) {
      cache[serializedArgs] = this.store[method].apply(this, args);
    }
    return cache[serializedArgs];
  };
}());

这是一个示例用法:

// Fires a request
cachedStore.call(this, 'findAll', 'blog-post');
// Returns from cache
cachedStore.call(this, 'findAll', 'blog-post');
// Returns from cache
cachedStore.call(this, 'findAll', 'blog-post');

// Fires a request
cachedStore.call(this, 'findRecord', 'blog-post', 123);
// Returns from cache
cachedStore.call(this, 'findRecord', 'blog-post', 123);
// Returns from cache
cachedStore.call(this, 'findRecord', 'blog-post', 123);

这有什么帮助吗?

关于javascript - 如何在 ember 数据中缓存查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30009059/

相关文章:

javascript - 用于 coffeescript 的 textmate 包

jquery - jQuery UI 日期选择器是否有任何修改以添加时间选择?

ruby-on-rails - 在单个页面上停止片段缓存 - Spree

javascript - 如何计算函数的参数数量,在 javascript 中,包括可选参数?

javascript - 坚持从表单元素进行简单计算

c# - 如何清理异常字符串以便可以通过 Javascript Alert 显示?

javascript - 怎么针对这个黎类的 sibling ?

php - 发送多个应用程序协议(protocol)请求(类似于 mailto : )

asp.net - 如何停止 ASP.NET Webforms 页面缓存不同版本

php - Symfony2 中的 Http 缓存