PDA

View Full Version : How to add mixin dynamically?



Ex_Soft
5 Jul 2012, 3:27 AM
Ext.define("TestMixin", {
testMixinFunction: function() {
this.name = this.name + " (from TestMixin.testMixinFunction())";
}
});

Ext.define("TestClassWithMixin", {
mixins: {
testMixin: "TestMixin"
},

config: {
name: "undefined"
},

constructor: function(config) {
this.initConfig(config);

return this;
},

foo: function() {
this.testMixinFunction();
}
});

works fine:


Ext.onReady(function() {
var
o = Ext.create("TestClassWithMixin", { name: "TestClassWithMixin" });

o.foo();
});

How to add mixin (e.g., "TestMixin") to


Ext.define("TestClassWithoutMixin", {
config: {
name: "undefined"
},

constructor: function(config) {
this.initConfig(config);

return this;
},

foo: function() {
this.testMixinFunction();
}
});

dynamically?

sdt6585
5 Jul 2012, 2:17 PM
Do you need a generic way to do this with all mixins or just need access to some functions of one of the mixins? It would be difficult to add a mixin to an existing object since they hook into their...mixee (not sure what a mixins target is called and I assume ice cream is out) at different points during initialization. You could do one of two other things though.

If you just need access to a function or two, you could extend them into your object using call/apply:


Ext.define("TestClassWithoutMixin", {
config: {
name: "undefined"
},


constructor: function(config) {
this.initConfig(config);


return this;
},


foo: function(args) {
var mixin = new TestMixin(mixinArgs);
mixin.testMixinFunction.apply(this, args);
}
});



Alternatively, you could make a member function that takes itself, reconstructs itself using it's prototype constructor, and adds the mixin in at that point, then overwrites it's memory pointer...that would take a little more mental energy than I've got right now though, so let me know how it goes.

-Stephen

lsdriscoll
24 Sep 2012, 12:48 AM
Instead of



...

mixins: {
mixable: 'My.Mixin'
}

...


Do



Ext.define('My.SubClass',{
extend: 'My.Class',

requires: ['My.Mixin'],

constructor: function(config){
Ext.apply(this, config);

this.self.mixin('mixable', My.Mixin);

// and if necessary...
this.mixins.mixable.constructor.call(this);

this.callParent(arguments);
}

});


The params for Ext.Base.mixin are:
A string to represent the mixin - can be whatever you choose.
The actual Class object of the mixin (which is why we need the requires)
If for some reason you cannot require the mixin in the definition, use Ext.require with a callback.

FYI, I have not tested it outside the constructor, but in theory it should still work - you just sure you apply the mixin before you try to use it's features.