2013-11-10 6 views
4

나는 knockoutjs을 사용하고 있으며 나는 그것에 익숙하지 않다. 선택한 값에 따라 모델 데이터를 변경하고 싶습니다. 그래서 내 AppModel에서, 내가 바꾸고 싶은 배열을 구독하고 있습니다. 하지만 작동하지 않는거야?. 여기 내 코드는 다음과 같습니다.knockoutjs 가입이 작동하지 않습니까?

var filteredStocks = []; 
function viewModel(model) { 
     this.isGeneral = ko.observable(model.generalStockEnabled); 
     this.stocks = ko.observable();; 
     if (model.generalStockEnabled === true) 
     { 
      filteredStocks = $.grep(model.stocks, function (v) { 
       return v.sourceID === -1; 
      }); 
     } 
     else 
     { 
      filteredStocks = $.grep(model.stocks, function (v) { 
       return v.sourceID !== -1; 
      }); 
     } 
     // If drop downlist changed 
     var dropDownListSelectedValue = $('#enableGeneratInventorydl :selected').val(); 
     this.stocks.subscribe(function() { 
      if (dropDownListSelectedValue === "True") { 
       filteredStocks = $.grep(model.stocks, function (v) { 
        return v.sourceID === -1; 
       }); 
       this.stocks(filteredStocks) 
       this.isGeneral(true); 
      } 
      else 
      { 
       filteredStocks = $.grep(model.stocks, function (v) { 
        return v.sourceID !== -1; 
       }); 
       this.stocks(filteredStocks) 
       this.isGeneral(false); 
      } 
     }, this); 

     this.stocks = ko.observableArray(filteredStocks); 

드롭 다운 목록 값을 변경하면 다음과 같습니다. 주식 가치는 동일하게 유지됩니까?

도움이 되셨습니까?

답변

9

다른 관찰 가능 변수에 stocks 변수를 다시 할당하기 때문에 문제가 나타납니다.

this.stocks = ko.observable(); 

를 그리고이 관찰에 가입 : 그래서 먼저 않습니다. 하지만 나중에 :

this.stocks = ko.observableArray(filteredStocks); 

이것은 다른 관찰 가능 항목과 stocks을 연결합니다. 서브 스크립 션은 첫 번째 할당의 원본 관찰 가능 항목에 대한 것입니다. 짧은 예를 들어,이 바이올린을 참조하십시오 http://jsfiddle.net/9nGQ9/2/

이 솔루션은 this.stocks = ko.observableArray();

this.stocks = ko.observable();

를 교체하고

+0

this.stocks(filteredStocks);this.stocks = ko.observableArray(filteredStocks);

이 답변 주셔서 감사합니다 대체하는 것 . 그것은 나를 위해 일했습니다. – user123456

+0

저장된 내 하루 :-D – chris

관련 문제