두 개의 다른 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());
});
녹아웃 3.1 (어제 공개)을 기반으로 한 새로운 대답보기 http://stackoverflow.com/questions/22198994/knockout-select-binding-not-remembering-value-when-options-added-late –