javascript - Pass object by reference to a returned function -
validations = [] isempty = (string) -> string '' or string undefined or string == null createvalidation = (scopevariable, expected, responsetext, inverse) -> if inverse == undefined inverse = false if !inverse returningvalidation = -> if scopevariable isnt expected $scope.response.text = responsetext $scope.response.class = 'text-danger' return false true else returningvalidation = -> if scopevariable expected $scope.response.text = responsetext $scope.response.class = 'text-danger' return false true returningvalidation validatecredentials = -> validated = true validations.map (validate) -> if !validate() validated = false validated $scope.register = -> if validatecredentials() #account.register $scope.form, (response) -> #if response.user_created true $scope.response.text = '...' $scope.response.class = 'text-success' validations.push createvalidation $scope.form.termschecked, true, '...' validations.push createvalidation $scope.form.password, $scope.form.passwordrepeat, '...' inverse = true validations.push createvalidation $scope.form.password, undefined, '...', inverse validations.push createvalidation $scope.form.password, '', '...', inverse
i have angularjs app form validation i'm triying create. there's function being created each kind of validation. supposed passed $scope.form.input
object each input. looks it's getting passed value. don't know how works in kind of js closure.
any kind of information helpfull.
in javascript, cannot pass simple types (string, numbers, booleans) reference. alternative, can pass function gets value looking for. example, instead of passing in $scope.form.termschecked
, pass in function returns value of $scope.form.termschecked
.
here example, written in javascript because coffeescript isn't good.
createvalidation = function(valueprovider, expected, responsetext, inverse) { // skipping bunch of code brevity... returningvalidation = function() { var scopevaraible = valueprovider(); console.log(scopevariable); // validation stuff... } return returningvalidation; } validations.push( createvalidation(function() { return $scope.form.termschecked; }, true, '...');