我有多个使用远程加载 JSON 数据的树存储的自定义树选择器实例。其中一些请求的延迟长达 25 秒。
那么,有没有办法可以在加载数据后缓存数据以供将来使用?
我检查了文档,特别是 LocalStorageProxy,但无法处理 JSON 数据。
谢谢。
最佳答案
这是一个代理,它将根据 url 缓存其响应
(function(){
// Key is the url, value is the response from the AJAX request
var requestCache = {};
/**
* A proxy that caches GET requests.
*/
Ext.define('Common.proxy.CachingRestProxy', {
extend: 'Ext.data.proxy.Rest',
alias: 'proxy.cachingrest',
statics: {
clearCache: function() {
requestCache = {};
}
},
createCacheKeyFromRequest: function (request) {
var url = request.getUrl();
var questionMarkIndex = url.indexOf('?');
var queryString = '';
// Don't want to include the cache buster in the cacheKey
if (questionMarkIndex > -1) {
queryString = url.substring(questionMarkIndex);
} url = url.substring(0, questionMarkIndex);
var queryStringObj = Ext.Object.fromQueryString(queryString);
delete queryStringObj[this.cacheString];
var params = Ext.apply(queryStringObj, request.getParams());
return url + JSON.stringify(params);
},
// Overridden to use GET requests from the cache if available
sendRequest: function(request) {
// The cacheKey is just a non readable string that includes all the data that makes up a unique rest call,
// including the url and the param keys and values.
var cacheKey = this.createCacheKeyFromRequest(request);
var cachedResponse = requestCache[cacheKey];
if(cachedResponse){
this.processResponse(true, request.getOperation(), request, cachedResponse);
return request;
} else {
return this.callParent([request]);
}
},
// Overridden to cache GET responses
processResponse: function(success, operation, request, response) {
this.callParent(arguments);
if (success && this.getMethod(request).toUpperCase() == 'GET'){
requestCache[this.createCacheKeyFromRequest(request)] = response;
}
}
});
})();
你只需像使用 RestProxy 一样使用它
proxy: {
type: 'cachingrest',
url: '/compose/api/v1/vocabularies',
...
}
关于javascript - ExtJS--如何缓存树数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29238746/