为什么这些记录没有存储在缓存中?

时间:2014-05-13 14:26:34

标签: javascript ember.js ember-data

我希望在收到记录后暂存我的记录,但我无法弄清楚如何记录。根据文档,您可以致电this.store.push('model', record),但它似乎无法正常工作。每次调用路由时,Ember都会从服务器请求数据,我只想这样做一次,并在从服务器获取后使用本地存储。

如果我按照Documentation的建议尝试调试它,我知道没有缓存:

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);
            });
        });
    }
});

1 个答案:

答案 0 :(得分:1)

this.store.find('type')将始终调用服务器以获取记录。如果您只想在ApplicationRoute中对服务器进行调用,然后使用find而不是all,请使用多次点击路径内的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');
    }
  }
});

延迟加载模型

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

实施例

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

您没有在适配器上定义主键,而是在序列化程序

this.store.typeMapFor(Pd.Product)

缓存不再存在,它位于this.store.typeMaps或{{1}}。

该网站仍在引用旧版本的ember数据,直到发布了ember数据1.0,我假设您使用的是1.0 beta版本。此文档更新https://github.com/emberjs/data/blob/master/TRANSITION.md