Mixins dactilografiat

voturi
6

Mă joc în jurul cu typescript, și am câteva mixins funcționale , Eventableși Settable, pe care aș vrea să mixin într - o Modelclasă (pretinde că e ceva de genul un 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);

Codul de mai sus funcționează bine, dar nu ar compila dacă am încercat să folosească una dintre metodele mixte în , cum ar fi (new Model()).set('foo', 'bar').

Eu pot lucra în jurul valorii de acest lucru prin

  1. adăugând interfacedeclarații pentru mixins
  2. declararea dummy get/ set/ on/ triggermetode în Modeldeclarația

Există un mod curat în jurul declarațiilor false?

Întrebat 04/10/2012 la 04:20
sursa de către utilizator
În alte limbi...                            


3 răspunsuri

voturi
12

Iată un mod de abordare mixins folosind interfacesși o static create()metodă. Interfețe sprijină moștenire multiplă , astfel încât vă împiedică să fi nevoie să redefinească interfacespentru mixins dumneavoastră și static create()metoda are grija de a da înapoi o instanță de Model()drept IModel(The <any>este necesară exprimate pentru a suprima un avertisment compilator.) Va trebui să duplicat toate definițiile membre pentru dvs. Modelpe IModelcare e de rahat , dar se pare ca cel mai curat mod de a realiza ceea ce doriți în versiunea curentă a dactilografiate.

edita: Am identificat o abordare ușor mai simplu de a mixins de sprijin și au creat chiar și o clasă de ajutor pentru a le defini. Detalii pot fi găsite aici .

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');
Publicat 04/10/2012 la 06:46
sursa de către utilizator

voturi
3

Cea mai curata mod de a face acest lucru, althought necesită în continuare declarații de tip dublu, este de a defini mixin ca un 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");

O alternativă la utilizarea interfețe este să-l hack cu clase (deși, din cauza multiple moștenire, va trebui să creați o interfață comună pentru 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.

Așa cum am comentat răspunsul lui Steven, mixins într-adevăr ar trebui să fie o caracteristică dactilografiate.

Publicat 04/10/2012 la 07:04
sursa de către utilizator

voturi
1

O soluție este să nu utilizeze sistemul de clasă dactilografiat, ci doar Systeme de tipuri și interfețe, în plus față de cuvântul cheie „nou“.

    //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 !
Publicat 23/01/2013 la 00:34
sursa de către utilizator

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