Created
May 2, 2015 18:11
-
-
Save RinatMullayanov/45c18c8001cef4330343 to your computer and use it in GitHub Desktop.
Mixins in Typescript
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
// 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