Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's one way to approach mixins using <code>interfaces</code> and a <code>static create()</code> method. Interfaces support multiple inheritance so that prevents you from having to redefine the <code>interfaces</code> for your mixins and the <code>static create()</code> method takes care of giving you back an instance of <code>Model()</code> as an <code>IModel</code> (the <code>&lt;any&gt;</code> cast is needed to supress a compiler warning.) You'll need to duplicate all of your member definitions for <code>Model</code> on <code>IModel</code> which sucks but it seems like the cleanest way to achieve what you want in the current version of TypeScript. </p> <p><strong>edit: I've identified a slightly simpler approach to supporting mixins and have even created a helper class for defining them. Details can be found <a href="http://typescript.codeplex.com/discussions/398391" rel="noreferrer">over here</a>.</strong></p> <pre><code>function asSettable() { this.get = function(key: string) { return this[key]; }; this.set = function(key: string, value) { this[key] = value; return this; }; } function asEventable() { this.on = function(name: string, callback) { this._events = this._events || {}; this._events[name] = callback; }; this.trigger = function(name: string) { this._events[name].call(this); } } class Model { constructor (properties = {}) { }; static create(): IModel { return &lt;any&gt;new Model(); } } asSettable.call(Model.prototype); asEventable.call(Model.prototype); interface ISettable { get(key: string); set(key: string, value); } interface IEvents { on(name: string, callback); trigger(name: string); } interface IModel extends ISettable, IEvents { } var x = Model.create(); x.set('foo', 'bar'); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload