- In Flight, a mixin is a function which assigns properties to a target object (represented by the
this
keyword). - A typical mixin defines a set of functionality that will be useful to more than one component.
- One mixin can be applied to any number of Component definitions.
- One Component definition can have any number of mixins applied to it.
- Each Component defines a core mixin within its own module.
- A mixin can itself have mixins applied to it.
Mixin definitions are like Component definitions but without the call to
defineComponent
.
define(function(require) {
function withDropdown() {
this.openDropdown = function() {
//...
};
this.selectItem = function() {
//...
};
}
// return the mixin function
return withDropdown;
});
In the Component definition, pass the required mixins as arguments to the
defineComponent
function:
define(function(require) {
var defineComponent = require('flight/lib/component');
var withDialog = require('mixins/with_dialog');
var withDropdown = require('mixins/with_dropdown');
return defineComponent(fancyComponent, withDialog, withDropdown);
function fancyComponent() {
//...
}
});
Under the covers, Components add mixins using Flight's compose
module, which
amongst other things, prevents mixins from clobbering existing method names. If
you ever need to apply a mixin to something other than a component (e.g. to
another mixin), you can invoke compose.mixin
directly:
define(function(require) {
var compose = require('flight/lib/compose');
var withPositioning = require('mixins/with_positioning');
function withDialog() {
//mix withPositioning into withDialog
compose.mixin(this, [withPositioning]);
//...
}
// return the mixin function
return withDialog;
});
The attributes
method is available to both component and mixin modules. When
used with mixins it will not overwrite attributes already defined in the
component module.
/* mixins/big_button */
define(function(require) {
function bigButton() {
this.attributes({
buttonClass: 'js-button-big'
});
}
return bigButton;
});
Existing Components can act as base components from which additional Components can be made.
For example, let's say all your components need to iplement some touch screen behavior and also
override Flight's default trigger
function. Instead of having to add these mixins to every component,
you can use them to create a base component (components/base
) which all other components will extend.
define(function(require) {
var defineComponent = require('flight/lib/component');
var withTouchScreen = require('mixins/with_touchscreen');
var withCustomTrigger = require('mixins/with_custom_trigger');
return defineComponent(withTouchScreen, withCustomTrigger);
});
Component constructors have a mixin
method which can be used to create a new Component constructor
based on the original:
define(function(require) {
var Base = require('components/base');
return Base.mixin(shoppingCart);
function shoppingCart() {
//..
}
});