Created
December 9, 2016 01:05
-
-
Save pentaphobe/b58c7399d6a114fd32f5885ad9887358 to your computer and use it in GitHub Desktop.
Compose controller functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Late night framework experiment with @pmarabeas | |
* | |
*/ | |
'use strict'; | |
var angular = require('angular'); | |
function compose(/** controllers */) { | |
var allControllers = Array.prototype.slice.call(arguments), | |
combinedDependencies = [], | |
functions = [], | |
argumentMappings = []; | |
allControllers | |
.filter(function(ctrl) { | |
return angular.isDefined(ctrl); | |
}) | |
.forEach(function(controller) { | |
var diArray, | |
fn; | |
if(angular.isArray(controller)) { | |
fn = controller.pop(); | |
diArray = controller; | |
} else if(angular.isArray(controller.$inject)) { | |
fn = controller; | |
diArray = controller.$inject; | |
} else { | |
throw new TypeError('composeControllers: Controllers being composed must either have dependencies defined in the array style or via $inject'); | |
} | |
functions.push(fn); | |
argumentMappings.push(diArray.map(function(dependency) { | |
var dependencyIndex = combinedDependencies.indexOf(dependency); | |
if(dependencyIndex === -1) { | |
combinedDependencies.push(dependency); | |
dependencyIndex = combinedDependencies.length - 1; | |
} | |
return dependencyIndex; | |
})); | |
}); | |
function composedController() { | |
var _this = this, | |
args = Array.prototype.slice.call(arguments); | |
functions.forEach(function(fn, idx) { | |
fn.apply(_this, argumentMappings[idx].map(function(val) { | |
return args[val]; | |
})); | |
}); | |
} | |
combinedDependencies.push(composedController); | |
return combinedDependencies; | |
} | |
module.exports = compose; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment