2012-03-05 1 views
1

두 개의 다른 AJAX 호출을 통해 <select />의 현재 값과 사용 가능한 옵션을 모두 가져와야합니다 (두 가지 이유 때문에 대기열에 넣을 수는 없습니다).AJAX를 통해 옵션을 바인딩 할 때 선택 요소의 기본값을 Knockout으로 전달할 수 있습니까?

중요한지는 모르겠지만 매번 사용 가능한 옵션을 읽는 호출 전에 현재 값을 읽는 호출이 완료됩니다.

녹아웃 2.0.0과 녹아웃 매핑 2.0.3을 사용하여 data-bind="options: values, value: valueComputed"으로 선택을 제한했지만 사용 가능한 옵션을 가져 오는 호출이 완료 될 때까지 Knockout이 첫 번째 AJAX 호출에 의해 설정된 값을 제거하거나 무시한다는 것을 알았습니다. 현재 값을 설정할 수 없습니다.

이 정보가 맞습니까? Knockout에게 "현재 값입니다. 사용 가능한 옵션을 사용할 수있게되면 선택할 수 있습니까?"

몇 가지 테스트가 끝난 후 나는 kludge가 생겼다. select 값에 대한 일반 관측 값을 바인딩하는 대신, 값을 가로 채고 새로운 값이있는 경우 계산 된 관측 값을 사용했다. 정의되지 않았습니다.

나는 악한 일을하고 있습니까?

jsFiddle 예 : http://jsfiddle.net/KeNUU/

내가 사용 자바 스크립트 코드 :

var viewModel = function() { 
    var self = this; 

    // The underlying observable where 
    // the selected value is stored. 
    self.value = ko.observable(); 

    // The observable bound to 
    // the value of the drop down. 
    self.values = ko.mapping.fromJS([]); 

    // Use a computed observable to intercept the undefined 
    // value placed by KnockOut when binding the drop down. 
    self.valueComputed = ko.computed({ 
     "read": function() { 
      return ko.utils.unwrapObservable(self.value); 
     }, 
     "write": function (value) { 
      // Update the underlying observable only when 
      // there is a value, if it's undefined ignore it. 
      if (value) { 
       self.value(value); 
      } 
     } 
    }); 

    // Simulate the AJAX request which fetches the actual value, 
    // this request must complete before the second one. 
    setTimeout(function() { 
     self.valueComputed("b"); 
    }, 1000 * 1); 

    // Simulate the AJAX request which fetches the available values, 
    // this reqest must complete after the first one. 
    setTimeout(function() { 
     ko.mapping.fromJS(["a", "b", "c", "d"], {}, self.values); 
    }, 1000 * 2); 
}; 

$(document).ready(function() { 
    ko.applyBindings(new viewModel()); 
}); 

답변

2

나는 당신이 당신에게 문제를 일으킬 것입니다 무엇을하고 있다고 생각하지 않지만, 당신이 우회하는 가치에 묶여있는 것이 당신의 선택에서 유효한 선택인지 확인하는 KO의 논리. 또한 빈 선택을 제공하기 위해 optionsCaption을 사용했다면 값을 지울 수 없습니다. 귀하의 경우, 그것은 중요하지 않을 것입니다.

더 쉬운 선택은 관찰 할 수없는 부분에 초기 값을 캐시 한 다음 목록이 돌아 오면 value을 채우는 데 사용하는 것입니다. 목록이 먼저 나온다면 초기 값이없고 정상적으로 작동 할 수 있습니다.

뭔가 같은 : 이제

setTimeout(function() { 
    self.initialValue = "b"; 
    self.value("b"); 
}, 1000 * 1); 

// Simulate the AJAX request which fetches the available values, 
// this reqest must complete after the first one. 
setTimeout(function() { 
    ko.mapping.fromJS(["a", "b", "c", "d"], {}, self.values); 
    if (self.initialValue) { 
     self.value(self.initialValue); 
     self.initialValue = null; 
    }  
}, 1000 * 2); 

http://jsfiddle.net/rniemeyer/gB3E5/

, 당신은 계산 관찰 절편을 드롭 다운에 모든 변경이있는의 (작은) 오버 헤드없이 선행을 처리합니다.

+0

녹아웃 3.1 (어제 공개)을 기반으로 한 새로운 대답보기 http://stackoverflow.com/questions/22198994/knockout-select-binding-not-remembering-value-when-options-added-late –

관련 문제