2013-09-26 3 views
0

knockoutJS 내에서 사용자 입력을 지원하고 입력에 텍스트 조작을 수행하는 계산 된 관찰 가능을 작성했습니다..replace() 표현식이 계산 된 관찰 가능 내에서 업데이트되지 않습니다.

이 관찰 가능 항목은 입력 필드와 레이블에 바인딩됩니다. 사용자가 새 이름을 입력 할 수있게하려는 의도이지만 사용자가 영숫자가 아닌 문자를 사용하지 못하도록하고 싶습니다. 이 함수는 바인딩의 평가와 문자열의 평가 모두에서 작동하지만 replace 함수는 업데이트하지 않는 것 같습니다. substring 함수는 작동합니다 (텍스트를 255 자로 제한 함).하지만 바꿔 치기에 정확히 설정되지 않은 항목이 있다고 생각합니다. 현재의 기능으로, 잘못된 문자가 입력되면 사용자는 toastr 경고를 수신하지만 replace 함수는 문자를 공백으로 대체하지 않습니다. 나는 어떤 제안을 주셔서 감사합니다.

HTML

<label class="reportNameTextBox" title="Click to edit report name" data-bind="text: NameFormatted() == null || NameFormatted().trim().length == 0 ? '[ Click To Enter Name ]' : NameFormatted(), css: { 'noData': NameFormatted() == null || NameFormatted().trim().length == 0 }"></label> 
      <input class="editInput" type="text" data-bind="value: NameFormatted" /> 

녹아웃

report.NameFormatted = ko.computed({ 
    read: function() { 
      return report.Name().substring(0, 255); 
      }, 
    write: function (value) { 
      var insertedText = value; 
      var Exp = /^[a-zA-Z0-9]*$/i; 
      if (!insertedText.match(Exp)) { 
      DisplayWarning('Attention', 'Non-alphanumeric may not be used.'); 
          return report.Name(insertedText.substring(0, 255)).replace(/[^a-zA-Z 0-9]+/g, ''); ; 
      } 
      else { 
      DisplayWarning('Success', 'yeah'); 
      return report.Name(insertedText.substring(0, 255)); 
      } 
      }, 
    owner: this 
}); 
+1

'report.Name() '대신'substring (0,255)'괄호에'.replace'를 묶을 필요가 없습니까? – SmokeyPHP

+0

또한 문자 클래스의 공백은 다른 어떤 문자와 같습니다. , 공백은 패턴에 의해 제거되지 않습니다. –

+0

@SmokeyPHP 그것은 좋은 눈이었습니다! 답변을 답장으로 보내 주시면 답변으로 표시하겠습니다. 감사합니다. – rlcrews

답변

0

나는 당신의 문제가이 선에 놓여 믿습니다 대신 report.Name (

return report.Name(insertedText.substring(0, 255)).replace(/[^a-zA-Z 0-9]+/g, ''); 

당신은 잘못된 객체에 replace 방법을 체인하고 substring)

return report.Name(insertedText.substring(0, 255).replace(/[^a-zA-Z 0-9]+/g, '')); 

대괄호 안에 replace 메서드를 옮기면 예상대로 작동합니다.

관련 문제