Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if object is instanceof mixin

Tags:

extjs

I'd like to check if the object x implements (is instance of) the mixin MyInterface:

Ext.define('MyInterface', {
    interfaceMethod: Ext.emptyFn
});

Ext.define('Foo', {
    mixins: {
        myInterface: 'MyInterface'
    }
});

var x = new Foo();

doesn't work work:

console.log(x instanceof MyInterface);

ugly workaround:

var isInstanceOfMyInterface = false;
for (var i in x.mixins) {
    if (x.mixins[i].$className == 'MyInterface') {
        isInstanceOfMyInterface = true;
    }
}
console.log(isInstanceOfMyInterface);

The workaround has one major issue: it doesn't work if a subclass of MyInterface is used.

jsfiddle

like image 572
Niko Sams Avatar asked Oct 18 '25 13:10

Niko Sams


1 Answers

A pattern the Ext core uses is to apply a mixin specific property so you can test for its existence. It's a lot cheaper than an instanceof check as well. For example:

Ext.define('MyInterface', {
    isMyInterface: true,
    interfaceMethod: Ext.emptyFn,
});

Ext.define('Foo', {
    mixins: {
        myInterface: 'MyInterface'
    }
});

var x = new Foo();
console.log(x.isMyInterface);
like image 125
Evan Trimboli Avatar answered Oct 21 '25 23:10

Evan Trimboli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!