In Flight, advice is a mixin (lib/advice.js
) that defines before
, after
and around
methods.
These can be used to modify existing functions by adding custom code. All
Components have advice mixed in to their prototype so that mixins can augment
existing functions without requiring knowledge of the original implementation.
Mixins will typically use the after
method to define custom initialize
behavior for the target component.
Run the customFunc
function before the existingFunc
function.
The name of the existing function (existingFunc
) you want to augment.
The function to be invoked before existingFunc
.
define(function() {
function withDrama() {
this.before('announce', function() {
clearThroat();
});
}
return withDrama;
});
Run the customFunc
function after the existingFunc
function.
The name of the existing function (existingFunc
) you want to augment.
The function to be invoked after existingFunc
.
define(function() {
function withDrama() {
this.after('leaving', function() {
slamDoor();
});
}
return withDrama;
});
Run the existingFunc
function in the middle of the customFunc
function. It's
similar to underscore's _wrap
function).
The name of the existing function (existingFunc
) you want to augment.
The function to wrap around existingFunc
. The existingFunc
function will be
passed to customFunc
as an argument.
The existing function is passed to the custom function as an argument so that it can be referenced. If the custom function does not call the existing function then it will replace that function instead of surrounding it:
define(function() {
function withDrama() {
this.around('announce', function(basicAnnounce) {
clearThroat();
basicAnnounce();
bow();
});
}
return withDrama;
});
Advice can be mixed in to non-components using the compose module:
// a simple module: 'test/myObj'
define(function() {
var myObj = {
print: function() {
console.log("hello");
}
};
return myObj;
});
// import myObj and augment it
define(function(require) {
var advice = require('flight/lib/advice');
var myObj = require('test/myObj');
// add advice functions to myObj
advice.withAdvice.call(myObj);
// augment print function
myObj.after('print', function() {
console.log("world");
});
});