2015-04-22 88 views
0
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闭包中起作用的。通过引用返回的函数传递对象

任何类型的信息将是有益的。

+0

你用1个参数声明你的验证函数,但用0参数调用它。那是故意的吗? (虽然我不太熟悉咖啡标题,所以我可能会误读它) –

+0

对不起,这不是它应该是。这是我,感到沮丧。现在是对的。 – Hotwer

回答

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, '...'); 
+1

不是通过值传递原语,而是通过JavaScript中的引用传递对象? – Nindaff

+0

哎呀!在我的部分错别字。我会修复它... –

+0

它的工作,但为什么只是传递的对象不够? – Hotwer