Last active
May 12, 2020 13:09
-
-
Save davestewart/1f8509ca17839e055485a160fea15ea3 to your computer and use it in GitHub Desktop.
TypeScript decorator to add Vue computed getters to a TypeScript class
This file contains hidden or 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
import Vue from 'vue' | |
export function cached (target: Function) { | |
// get descriptors | |
const descriptors: any = Object.getOwnPropertyDescriptors(target.prototype) | |
const getters = Object | |
.keys(descriptors) | |
.filter(key => descriptors[key].get && !descriptors[key].set) | |
// we have getters! | |
if (getters.length) { | |
// scope for accessors | |
let scope = null | |
// build caching layer | |
const cache = new Vue({ | |
computed: getters.reduce((output, key) => { | |
// cache reference to original accessors | |
const { get } = descriptors[key] | |
// create getter | |
output[key] = () => get.call(scope) | |
return output | |
}, {}) | |
}) | |
// update descriptors | |
getters.forEach(key => { | |
const descriptor = descriptors[key] | |
descriptor.get = function () { | |
scope = this | |
return cache[key] | |
} | |
// update original descriptor | |
Object.defineProperty(target.prototype, key, descriptor) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment