canjs / can-observable-mixin

Define properties on JavaScript classes
https://canjs.com
MIT License
2 stars 1 forks source link

Mixin - user convience tools #160

Open qantourisc opened 4 years ago

qantourisc commented 4 years ago

In canJS2 ? One could write var MyDefineMap = can.DefineMap.extend(my_mixin).extend({usual stuff})

So the general idea of mixin's as usual. Except it's not quite so straightforward with CanJS. Does CanJS include premade tools to do these kinds of things ?

Currently writing my own crude "solution" that will probably have a few edge cases:

export const MixinCanJs = function(superclass,...mixins){
    return mixins.reduce(
        (c, mixin) =>{
            let org_props = c.props;
            let ret = mixin(c);
            let plain = mixin(function(){});
            Object.defineProperty(ret,"props",{
                get: function(){
                    return {...c.props, ...plain.props};
                }
            });
            return ret;
        },
        superclass
    );
}
class A{
    static get props(){ return {a:0,b:1} }
    test(){
        console.log("A");
    }
};

//This is how you define a mixin
const log_test = superclass => class extends superclass {
    log(){
        console.log("test")
    }
};

const _B = superclass => class extends superclass {
    static get props(){ return {a:1} }
    test(){
        super.test();
        console.log("b");
    }
};

class B extends MixinCanJs(A,log_test,_B){};

(new B).log();
(new B).test();
console.log(B.props);