Last active
December 30, 2015 08:09
-
-
Save bestguy/7800836 to your computer and use it in GitHub Desktop.
Example client-side requirejs module for locally caching REST data.
Uses Durandal (durandaljs.com), Knockout, and Knockout Persist plugin (https://github.com/spoike/knockout.persist)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(function () { | |
var $ = require('jquery'); | |
var http = require('plugins/http'); // Durandal plugin | |
var instance = null; | |
var ko = require('knockout'); | |
function Meetings(maxAge) { | |
if (instance !== null) { | |
throw new Error("Cannot instantiate more than one Meetings, use Meetings.getInstance()"); | |
} | |
var self = this; | |
// Default expiration of 1 hour if undefined: | |
self.maxAge = maxAge || 60 * 60 * 1000; | |
self.meetings = ko.observableArray().extend({ | |
persist: 'meetings' // LocalStorage plugin | |
}); | |
self.lastRefresh = ko.observable(0).extend({ | |
persist: 'lastRefresh' // LocalStorage plugin | |
}); | |
self.refresh = function () { | |
return http.get('/api/me/meetings') // Local REST API | |
.then(function (meetings) { | |
self.meetings = meetings; | |
self.lastRefresh(new Date().getTime()); | |
}); | |
// Auth errors are exposed in getMeetings promise fail | |
} | |
self.cacheExpired = function() { | |
return new Date().getTime() - self.lastRefresh() > self.maxAge; | |
} | |
// Gets Meeting list, which may be cached | |
self.getMeetings = function () { | |
var deferred = $.Deferred(); | |
if (self.cacheExpired()) { | |
console.log('Cache Miss'); | |
self.refresh() | |
.then(function () { | |
deferred.resolve(self.meetings); | |
}) | |
.fail(function (err) { | |
deferred.reject(err); | |
}) | |
} else { | |
console.log('Cache Hit'); | |
deferred.resolve(self.meetings); | |
} | |
return deferred.promise(); | |
} | |
// Creates Meeting and expires cache | |
self.scheduleMeeting = function() { | |
self.lastRefresh(0); | |
return http.post('/api/me/meetings'); | |
} | |
} | |
Meetings.getInstance = function () { | |
if (instance === null) { | |
instance = new Meetings(); | |
instance.refresh(); | |
} | |
return instance; | |
}; | |
return Meetings.getInstance(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment