ExtJS--如何缓存树数据

ExtJS--how to cache tree data

我有多个使用远程加载 JSON 数据的 treestores 的自定义 treepicker 实例。其中一些请求的延迟长达 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',
    ...

}