Skip to content

Instantly share code, notes, and snippets.

@cameronhunter
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronhunter/398d7f091f7e52768843 to your computer and use it in GitHub Desktop.
Save cameronhunter/398d7f091f7e52768843 to your computer and use it in GitHub Desktop.
[Experimental] FlightJS component that intercepts and caches event data.
var defineComponent = require("core/component");
module.exports = defineComponent(eventDataCache);
function eventDataCache() {
this.defaultAttrs({
"requestEvent": "foo",
"requestCacheKey": "key",
"successEvent": "bar",
"successCacheKey": "key"
});
function getCacheKey(data, key) {
key.split('.').reduce(function(data, k) { return data[k]; }, data);
}
this.interceptEvent = function(e, data) {
var key = getCacheKey(data, this.attr.requestCacheKey);
var cached = key && this.cache[key];
if (cached) {
console.log("Cache hit for", key, cached);
cached.from_cache = true;
this.trigger(e.target, this.attr.successEvent, cached);
} else {
console.log("Cache miss for", key);
}
};
this.cacheEventData = function(e, data) {
var key = getCacheKey(data, this.attr.successCacheKey);
if (key && !data.from_cache) {
var cached = this.cache[key];
if (cached && JSON.stringify(cached) === JSON.stringify(data)) {
console.log("Cached data is already up to date");
e.stopImmediatePropagation();
} else {
console.log("Caching", key, data);
this.cache[key] = data;
}
}
};
this.after("initialize", function() {
this.cache = {};
this.on(this.attr.requestEvent, this.interceptEvent);
this.on(this.attr.successEvent, this.cacheEventData);
});
}

This is an experiment in unobtrusively caching event data in FlightJS. It's a component which effectively slides between a UI and data component, intercepting requests for data, and caching responses. It doesn't require cache invalidation because it does not prevent the data component from retrieving updated data when there's a cache hit. This allows us to create a snappier UI by providing the "last known" data, but still allowing the data component to fetch and trigger with the most recent data at a later stage.

If a "with_data" mixin existed with methods such as this.get and this.post, then this could be a mixin using advice to surround these functions with caching. Perhaps that's a cleaner way of implementing this functionality – this is just an experiment.

This could also be mixed with the flight-storage component, so that the cached data could be served from localStorage or IndexDB.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment