Skip to content

Instantly share code, notes, and snippets.

@michelsalib
Created April 22, 2015 15:52
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michelsalib/d60ef267ae0a8f91e64d to your computer and use it in GitHub Desktop.
Save michelsalib/d60ef267ae0a8f91e64d to your computer and use it in GitHub Desktop.
Typescript @timestampable annotation
@timestampable
class Dog {
public name: string = 'Paul';
}
function timestampable(func) {
return <any>(function() {
var genericConstructor = () => {};
genericConstructor.prototype = func.prototype;
var instance = new genericConstructor();
func.apply(instance, <any>arguments);
instance.createdAt = new Date();
(<any>Object).observe(instance, (changes) => {
if (changes.length == 1 && changes[0].name == 'updatedAt') {
return;
}
instance.updatedAt = new Date();
});
return instance;
});
}
// create my dog
var d = new Dog();
console.log(d.name, (<any>d).createdAt, (<any>d).updatedAt);
// change his name in 100ms
setTimeout(() => {
d.name = 'Pierre';
// let time for updatedAt to be computed and print next tick
setTimeout(() => {
console.log(d.name, (<any>d).createdAt, (<any>d).updatedAt);
});
}, 100);
@robertpenner
Copy link

That's really creative!

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