-
-
Save ThomasBurleson/11237264 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
var _ = require('underscore'); | |
module.exports = function () { | |
var proto, | |
injections = []; | |
// define constructor function | |
/*jshint validthis:true */ | |
function ctor () { | |
var i, len, injectName, key, prop; | |
// assign injected dependencies as instance properties | |
if (ctor.$inject) { | |
for (i = 0, len = ctor.$inject.length; i < len; i++) { | |
injectName = ctor.$inject[i]; | |
this[injectName] = arguments[i]; | |
} | |
} | |
// automatically bind private callbacks (methods beginning with _on) | |
for (key in this) { | |
prop = this[key]; | |
if (typeof prop === 'function' && key.indexOf('_on') === 0) { | |
this[key] = _.bind(this[key], this); | |
} | |
} | |
// call init pseudo-constructor if present | |
if (this.init) { | |
this.init.apply(this, arguments); | |
} | |
} | |
proto = ctor.prototype; | |
for (var i = 0, len = arguments.length; i < len; i++) { | |
// merge each set of properties into the prototype | |
_.extend(proto, arguments[i]); | |
// gather all mixin injections | |
if (arguments[i].$inject) { | |
injections = injections.concat(arguments[i].$inject); | |
} | |
} | |
// save injection names as a property on constructor | |
if (injections.length > 0) { | |
ctor.$inject = _.uniq(injections); | |
} | |
return ctor; | |
}; |
Perhaps a better solution is to create a minSafe( )
instead of an ExtJS-like mixin( )
.
Consider the sample below where I use a minSafe( )
to hide how I annotate the construction function:
// Export the HomeController Class
module.exports = require( 'ng-minSafe' )(
HomeController,
['urlUtil', '$scope', '$http', 'session']
);
// ************************************************************
// HomeController Class
// ************************************************************
function HomeController(urlUtil, $scope, $http, session)
{
$scope.submit = onSubmit;
function onSubmit()
{
var user = $scope.user;
if (user.password !== user.verifyPassword) {
throw new Error('Mismatched passwords!');
}
var config = {
orgName: urlUtil.orgName,
password: user.password,
};
return $http.post( urlUtil.getResetPasswordUrl(), config)
.then(_onResetPasswordSuccess, _onResetPasswordFailure);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
mixin()
idea is a very interesting idea... I would recommend not using an anonymous function for the init; since it unintentionally hides the purpose of the mixin class. Wonder what you think of this change: