English 中文(简体)
如何在 Backbone 模式中创建缓存/ 模拟器
原标题:How to make a cache/memorizer in BackboneModel

s 假设我有一个视图, 可以生成模型. fetch (), 然后请求服务器 。

I would like to implement:
1) A checker able to memorise the result
2) refresh the result (making the request to the server) only if the last request to the server is older than ten minutes.

What should I do?
Is there already a piece of code to make that?

define([], function() {

    var MyModel = Backbone.Model.extend({

    url: function () {
        return "http://localhost/restapi/model/";
    },

    fetch () {
        if(diffTime > 10minutes) {
            // make request to the server
        }
        else {
            // return memo
        }
    }    

    });

});
问题回答

您需要推翻 Backbone. sync 方法 < a href=> "http://documentcloud.github.com/backbone/#Sync" rel="no follow" >http://docuscloud.github.com/backbone/#Sync 。

此代码可以保存到本地存储处, 以实施缓存 < a href="http://documentcloud.github.com/backbone/docs/backbone-localstorage.html" rel="no follow" >http://documentcloud.github.com/backbone/docs/backbone-localstorage.html 。

如果数据超过10分钟, 在“ 读取” 选项中添加一些逻辑来从服务器获取数据是很简单的 。

正如 codmonkey 所说, 本地存储将是一个不错的选择。 但如果您不想为此使用图书馆, 您可以使用此类来扩展需要缓存功能的模型 。

var CachedModel = Backbone.Model.extend({

    lastFetch: null,    // millisec.
    cache: { }
    fetch: function () {
        if(!this.lastFetch || (lastFetch - Date.now() > 10*60*1000) {
            // make request to the server
        }
        else {
            // return this.cache
        }
    }    

});




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签