Mixins na psacím stroji

hlasů
6

Hraju si s strojopisu, a já jsem dostal pár funkčních mixins , Eventablea Settable, že bych chtěl mixin do Modeltřídy (předstírat, že je to něco jako model backbone.js):

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 = {}) {
  };
}

asSettable.call(Model.prototype);
asEventable.call(Model.prototype);

Výše uvedený kód funguje dobře, ale nebude sestavovat, jestli jsem se snažil použít jednu ze smíšených-in metod, jako je (new Model()).set('foo', 'bar').

Mohu tento problém vyřešit tím,

  1. přidání interfaceprohlášení pro mixins
  2. deklarovat falešné get/ set/ on/ triggermetody v Modelprohlášení

Je tam čistý způsob, jak obejít prohlášení figuríny?

Položena 04/10/2012 v 04:20
zdroj uživatelem
V jiných jazycích...                            


3 odpovědí

hlasů
12

Zde je jeden způsob, jak přistupovat mixins pomocí interfacesa static create()metody. Rozhraní podporuje vícenásobnou dědičnost, takže vám brání museli nově definovat interfacespro mixins a static create()metoda stará dát zpátky instanci Model()jako IModel(dále jen <any>je potřeba cast potlačit varování kompilátoru.) Budete muset duplikovat všechny váš členský definice Modelna IModelkterých vysává, ale zdá se, jako nejčistší způsob, jak dosáhnout toho, co chcete v aktuální verzi strojopisu.

edit: Identifikoval jsem trochu jednodušší přístup k podpoře mixins a dokonce vytvořili pomocnou třídu pro jejich definování. Podrobnosti lze nalézt tady .

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 <any>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');
Odpovězeno 04/10/2012 v 06:46
zdroj uživatelem

hlasů
3

Nejčistší způsob, jak to udělat, Ačkoli jde stále vyžaduje deklarace typu double, je definovat mixin jako modul:

module Mixin {
    export function on(test) {
        alert(test);
    }
};

class TestMixin implements Mixin {
    on: (test) => void;
};


var mixed = _.extend(new TestMixin(), Mixin); // Or manually copy properties
mixed.on("hi");

Alternativou k použití rozhraní je to hack s třídami (Ačkoli díky vícenásobné dědičnosti, budete muset vytvořit společný-rozhraní pro mixins):

var _:any;
var __mixes_in = _.extend; // Lookup underscore.js' extend-metod. Simply copies properties from a to b

class asSettable {
    getx(key:string) { // renamed because of token-clash in asEventAndSettable
        return this[key];
    }
    setx(key:string, value) {
        this[key] = value;
        return this;
    }
}

class asEventable {
    _events: any;
    on(name:string, callback) {
        this._events = this._events || {};
        this._events[name] = callback;
    }
    trigger(name:string) {
        this._events[name].call(this);
  }
}

class asEventAndSettable {
   // Substitute these for real type definitions
   on:any;
   trigger:any;
   getx: any;
   setx: any;
}

class Model extends asEventAndSettable {
    /// ...
}

var m = __mixes_in(new Model(), asEventable, asSettable);

// m now has all methods mixed in.

Jak jsem již uvedl na Stevena odpovědi mixins ve skutečnosti mělo být rys strojopisem.

Odpovězeno 04/10/2012 v 07:04
zdroj uživatelem

hlasů
1

Jedním z řešení je nepoužívat třídní systém strojopisem, ale stačí Systeme typů a rozhraní, kromě klíčového slova ‚nové‘.

    //the function that create class
function Class(construct : Function, proto : Object, ...mixins : Function[]) : Function {
        //...
        return function(){};
}

module Test { 

     //the type of A
    export interface IA {
        a(str1 : string) : void;
    }

    //the class A 
    //<new () => IA>  === cast to an anonyme function constructor that create an object of type IA, 
    // the signature of the constructor is placed here, but refactoring should not work
    //Class(<IA> { === cast an anonyme object with the signature of IA (for refactoring, but the rename IDE method not work )
    export var A = <new () => IA> Class(

        //the constructor with the same signature that the cast just above
        function() { } ,

        <IA> {
            //!! the IDE does not check that the object implement all members of the interface, but create an error if an membre is not in the interface
            a : function(str : string){}
        }
    );


    //the type of B
    export interface IB {
        b() : void;
    }
    //the implementation of IB
    export class B implements IB { 
        b() { }
    }

    //the type of C
    export interface IC extends IA, IB{
        c() : void;
        mystring: string;
    }

     //the implementation of IC
    export var C = <new (mystring : string) => IC> Class(

        //public key word not work
        function(mystring : string) { 

            //problem with 'this', doesn't reference an object of type IC, why??
            //but google compiler replace self by this !!
            var self = (<IC> this);
            self.mystring = mystring;
        } ,

        <IC> {

            c : function (){},

            //override a , and call the inherited method
            a: function (str: string) {

                (<IA> A.prototype).a.call(null, 5);//problem with call and apply, signature of call and apply are static, but should be dynamic

                //so, the 'Class' function must create an method for that
                (<IA> this.$super(A)).a('');
            }

        },
        //mixins
        A, B
    );

}

var c = new Test.C('');
c.a('');
c.b();
c.c();
c.d();//ok error !
Odpovězeno 23/01/2013 v 00:34
zdroj uživatelem

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more