如何使用Dojo Store进行客户端数据缓存?

时间:2013-12-03 03:55:46

标签: javascript dojo

我很难理解如何实施客户端缓存。在我的示例代码中,使用store.get(id)的每个调用都会创建一个新的HTTP请求。据我所知,数据不是从本地内存中检索的。

dojo/store/Cache的文档中,它明确指出在第一个GET请求完成后数据存储在本地内存缓存中。后续请求将从本地内存中提取。

但是,使用Firefox Web Inspector我看到我的代码每次都会创建一个新的HTTP请求。我究竟做错了什么?

代码:

require(["dojo/store/JsonRest", "dojo/store/Memory", "dojo/store/Cache", "dojo/domReady!"], function(JsonRest, Memory, Cache) {

    var restStore = new JsonRest({target:"/rest/Vendor/"});
    var memoryStore = new Memory({});
    var store = new Cache(restStore, memoryStore);

    var object = store.get("5").then(function(value) {
        console.log("Vendor Name: ", value.name);
    });

    var object = store.get("5").then(function(value) {
        console.log("Vendor Name: ", value.name);
    });

    var object = store.get("5").then(function(value) {
        console.log("Vendor Name: ", value.name);
    });

});

Web Inspector输出

[22:28:59.585] GET http://my-website-url.com/rest/Vendor/5 [HTTP/1.1 200 OK 596ms]
[22:28:59.588] GET http://my-website-url/rest/Vendor/5 [HTTP/1.1 200 OK 40ms]
[22:28:59.153] "Vendor Name: " "Company E"
[22:28:59.589] GET http://my-website-url/rest/Vendor/5 [HTTP/1.1 200 OK 36ms]
[22:28:59.196] "Vendor Name: " "Company E"
[22:28:59.235] "Vendor Name: " "Company E"

来自休息呼叫的JSON输出

[
    {"name":"Company A","vendorId":1,"active":1},
    {"name":"Company B","vendorId":2,"active":1},
    {"name":"Company C","vendorId":3,"active":1},
    {"name":"Company D","vendorId":4,"active":1},
    {"name":"Company E","vendorId":5,"active":1}
]

1 个答案:

答案 0 :(得分:2)

我认为你必须为JsonRest store和内存存储提供“idProperty”,因为“Cache”将尝试在其缓存中查找标识符为“5”的对象。由于您尚未指定哪个属性标识对象,因此它不会在缓存中找到条目并再次执行HTTP请求。

简而言之:我希望当你为商店指定idProperty时它会起作用,如下所示:

var restStore = new JsonRest({target:"/rest/Vendor/", idProperty: "vendorId"});
var memoryStore = new Memory({idProperty: "vendorId"});