Created
April 22, 2015 15:52
-
-
Save michelsalib/d60ef267ae0a8f91e64d to your computer and use it in GitHub Desktop.
Typescript @timestampable annotation
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
@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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's really creative!