通过引用传递对象返回的函数

时间:2015-04-22 23:12:26

标签: javascript angularjs coffeescript

validations = []

isEmpty = (string) ->
    string is '' or string is 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 is 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 is 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

我有一个AngularJS应用程序,我正在试图创建一个表单验证。每种验证都有一个功能。应该将$scope.form.input对象传递给每个输入。但它似乎正在通过价值传递。我真的不知道它在这种JS闭包中是如何工作的。

任何类型的信息都会有所帮助。

1 个答案:

答案 0 :(得分:3)

在javascript中,您不能通过引用传递简单类型(字符串,数字,布尔值)。作为替代方案,您可以传递一个获取您正在寻找的值的函数。例如,您可以传入一个返回$scope.form.termsChecked值的函数,而不是传递$scope.form.termsChecked

这是一个用JavaScript编写的例子,因为我的CoffeeScript不太好。

createValidation = function(valueProvider, expected, responseText, inverse) {
    // Skipping a bunch of your code for brevity...
    returningValidation = function() {
        var scopeVaraible = valueProvider();
        console.log(scopeVariable);
        // Now do some validation stuff...
    }
    return returningValidation;
}

validations.push(
    createValidation(function() { return $scope.form.termsChecked; }, true, '...');