2015-04-22 60 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