javascript之为什么这些记录没有存储在缓存中
我想在收到记录后对其进行缓存,但我不知道如何进行。根据文档,您可以只调用 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);
});
});
}
});
请您参考如下方法:
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');
}
}
});
示例
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 beta 版本。本文档已更新 https://github.com/emberjs/data/blob/master/TRANSITION.md
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



