2015-01-12 3 views
0

나는 결과에 따라 확인 될 때마다 체크 상자를 선택 해제하려면 노력하고 있어요,하지만 난 부울라는 오류가선택 취소 확인란은

function IndexVM() { 
    // Observable objects 
    this.Files = ko.observableArray([]); 

    this.CreateAML = function() { 
     var self = this; 

     for (var i = 0; i < self.Files().length; i++) { 
      if (self.Files()[i].Selected) { 
       $.ajax({ 
        type: "POST", 
        url: "Home/CreateAML", 
        dataType: 'json', 
        data: "{ 'File': " + ko.toJSON(self.Files()[i]) + "}", 
        contentType: "application/json", 
        success: function (response) { 
         self.Files()[i].Selected(response.d); //this is where the error is thrown 
       } 
      } 

    }; 
}; 
뷰 모델
기능

아니다

업데이트 :

function File() { 
    var self = this; 
    self.Selected = ko.observable(false); 
    // ...more properties 
}; 

function IndexVM() { 
    var self = this; 

    // Observable objects 
    self.Path = ko.observable(); 
    self.Files = ko.observableArray([]); 

    self.selectedFiles = ko.computed(function() { 
     return ko.utils.arrayFilter(self.Files(), function (file) { 
      return file.Selected(); 
     }); 
    }); 

    this.CreateAML = function() { 
     var self = this; 

     ko.utils.arrayForEach(self.selectedFiles(), function (file) { 
      $.ajax({ 
       url: "Home/CreateAMLTest", 
       contentType: "application/json; charset=utf-8", 
       data: ko.toJSON({ 
        File: ko.toJS(file) 
       }) 
      }).done(function (response) { 
       file.Selected(response.d); 
      }).fail(function (jqXHR, textStatus, errorThrown) { 
       // handle the error 
      }); 
     }); 
    }; 
}; 

답변

2

귀하의 코드에서 귀하의 File.Selected이 관찰 가능하지 않기 때문에 그 이유는 일반 부울 값입니다.

관찰 가능하도록 설정하거나 self.Files()[i].Selected = response.d;을 사용하여 설정하십시오. 나는 전자를 제안한다.

은 또한 코드에 몇 가지 다른 변경을 제안 :

function File() { 
    var self = this; 
    self.Selected = ko.observable(false); 
    // ...more properties 
} 

function IndexVM() { 
    var self = this; 

    self.Files = ko.observableArray([]); 

    self.SelectedFiles = ko.pureComputed(function() { 
     return ko.utils.arrayFilter(self.Files(), function (file) { 
      return file.Selected(); 
     }); 
    }); 

    this.CreateAML = function() { 
     ko.utils.arrayForEach(self.SelectedFiles(), function (file) { 
      $.ajax({ 
       type: "POST", 
       url: "Home/CreateAML", 
       contentType: "application/json; charset=utf-8", 
       data: ko.toJSON({ 
        File: ko.toJS(file) 
       }) 
      }).done(function (response) { 
       file.Selected(response.d); 
      }).fail(function (jqXHR, textStatus, errorThrown) { 
       // handle the error 
      }); 
     }); 
    }; 
} 

참고 :

  • File.Selected 지금 관측이다.
  • 편의상 지금은 SelectedFiles()이라고 계산되어 있습니다. 다른 장소에서도 필요하다고 생각합니다. 그리고 그렇지 않으면 여전히 의미가 향상되고 있습니다 CreateAML().
  • 나는 for 루프에서 ko.utils.arrayForEach()으로 전환했다. 이렇게하면 CreateAML()의 가독성에 긍정적 인 영향을 주며, creating functions in a loop (like the callbacks to .ajax()) is not recommended in JavaScript도 표시됩니다. (덧붙여 말하자면,이 안티 패턴의 사용은 콜백에서 i을 참조하지만 콜백이 실행될 때 i에 더 이상 포함되지 않는다고 생각하는 내용이 포함되어 있지 않습니다. 오류가 발생하지 않은 경우에도 루프가 발생했습니다
  • 문자열을 연결하여 JSON을 작성하는 것이 이상적이지는 않습니다. 순수한 접근 방식을 사용하는 것은 더 나은 (ko.toJSON({ File: ko.toJS(file) }).
  • 내가 Ajax 호출에서 "연기"sematics에 "성공"콜백로 전환
  • . 수동으로 모든 객체를 매핑하지 않으려면 knockout's mapping plugin에서
  • 봐 자신의 뷰 모델. 압도적으로 널리 채택 국제 대회에만 생성자
  • 이름은 모두 다른 식별자 camelCase에, 자바 스크립트에서 PascalCase 있습니다.이 IndexVM하지만 createAML, filesselectedFiles 것 그래서. 전환에 대해 생각.
+0

감사합니다. 감사합니다. this.selectedFiles = ko.pureComputed (function() { – Gericke

+0

어떤 버전의 knockout을 사용하고 있습니까? 3.2보다 작 으면'computed()'를 사용하십시오. [순수 계산] (http://knockoutjs.com/documentation/computed-pure.html)이 3.2에서 소개되었으므로 사용할 수 없다면 정상적인 것을 염두에 두지 마십시오. – Tomalak

+0

나는 3.0을 사용하고 있기 때문에 나의 이해는 잘 돌아 간다. – Gericke