为什么这些记录不存储在缓存中

Why are these records not stored in cache?

本文关键字:缓存 存储 记录 为什么      更新时间:2023-09-26

我想缓存我的记录一旦他们收到,但我不知道如何。根据文档,您可以调用this.store.push('model', record),但它似乎不起作用。Ember通过每次调用路由从服务器请求数据,我希望只这样做一次,并在从服务器获取数据后使用本地存储。

如果我尝试调试它按照建议的文档,我得到没有缓存:

Pd.__container__.lookup('store:main').recordCache 
// --> undefined

这是我的路由(我尝试缓存它):

Pd.ProductsRoute = Ember.Route.extend({
    model: function () {
        var promise = this.store.find('product');
        var that = this;
        promise.then(function(value) {
            // Caching supposed to happen here
            value.content.forEach(function(product){
                that.store.push('product', product); 
            });
        }, function(reason) {
            // on rejection
        });
        return promise;
    }
});

这是根据适配器(似乎工作良好):

Pd.ProductAdapter = DS.RESTAdapter.extend({
    primaryKey: 'nid', // DOES NOT WORK BUT I CAN LIVE WITH THAT (SEE WORKAROUND)
    findAll: function(store, type) {
        var url = 'ws/rest/products';
        return new Ember.RSVP.Promise(function(resolve, reject) {
            jQuery.getJSON(url).then(function(data) {
                Ember.Logger.debug("Received Products:"); // TRIGGERS EVERY TIME!
                var srcPattern = /src=["']([^'"]+)/;
                data.forEach(function(product){
                    product.id = product.nid;
                    product.field_image = srcPattern.exec(product.field_image)[1];
                });
                Ember.Logger.debug(data);
                Ember.run(null, resolve, {product: data});
            }, function(jqXHR) {
                jqXHR.then = null; // tame jQuery's ill mannered promises
                Ember.run(null, reject, jqXHR);
            });
        });
    }
});

this.store.find('type')将始终向服务器调用记录。如果你只想在ApplicationRoute中调用服务器一次,然后使用all过滤器,而不是使用find,这是多次命中的路由。

Pd.ApplicationRoute = Em.Route.extend({
  model: function(params){
    return Em.RSVP.hash({
       product: this.store.find('product'),
       somethingElse: otherPromise
    })
  }
});
Pd.ProductRoute = Em.Route.extend({
  model: function(params){
    return this.store.all('product');
  }
});

如果你只是想在商店里准备好你的产品,你甚至不需要返回它,或者在应用路由中使用它

Pd.ApplicationRoute = Em.Route.extend({
  model: function(params){
    this.store.find('product');
    return {foo:'bar'}; // or return nothing, it doesn't matter
  }
});

延迟加载模型

App.ProductRoute = Ember.Route.extend({
  hasPreLoaded: false,
  model: function() {
    if(this.get('hasPreLoaded')){
      return this.store.all('product');
    } else {
      this.toggleProperty('hasPreLoaded');
      return this.store.find('product');
    }
  }
});

例子http://emberjs.jsbin.com/OxIDiVU/482/edit

你不用在适配器上定义主键,它在序列化器上

Pd.ProductSerializer = DS.RESTSerializer.extend({
  primaryKey: 'nid'
});

缓存不再存在于this.store.typeMapFor(Pd.Product)this.store.typeMaps中。

在ember data 1.0发布之前,该站点仍然引用旧版本的ember data,我假设您使用的是1.0测试版。本文档是最新的https://github.com/emberjs/data/blob/master/TRANSITION.md