Skip to content

Instantly share code, notes, and snippets.

@RinatMullayanov
Created May 2, 2015 18:11
Show Gist options
  • Save RinatMullayanov/45c18c8001cef4330343 to your computer and use it in GitHub Desktop.
Save RinatMullayanov/45c18c8001cef4330343 to your computer and use it in GitHub Desktop.
Mixins in Typescript
// Disposable Mixin
class Disposable {
isDisposed: boolean;
dispose() {
this.isDisposed = true;
}
}
//Activatable Mixin
class Activitable {
isActive: boolean;
activate() {
this.isActive = true;
}
deactivate(){
this.isActive = false;
}
}
class SmartObject implements Disposable, Activitable {
constructor() {
setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
}
interact() {
this.activate();
}
// Disposable
isDisposed: boolean = false;
dispose: () => void;
//Activatable
isActive: boolean = false;
activate: () => void;
deactivate: () => void;
}
applyMixins(SmartObject, [Disposable, Activitable]);
var smartObj = new SmartObject();
setTimeout(() => smartObj.interact(), 1000);
////////////////////////////////////////
// In your runtime library somewhere
////////////////////////////////////////
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment