[英]Knockout observable array index in outside function
我有一個下拉菜單,允許用戶選擇某個月份。 一個可觀察的數組根據用戶選擇更改了我的傳單地圖的圖層(完美工作)。
現在,我需要用於另一個函數的選擇值myMonth
(從零開始的月份數),該函數將使用內容填充彈出窗口。 我只是在viewModel
函數之外找不到使用變量myMonth
的有效解決方案...非常感謝您的幫助!
這是我的代碼,其結果是: popupcontent = "Selected month: undefined"
var myMonth; //global variable myMonth
//oberservable array
function viewModel() {
this.choices = ko.observableArray([
"January","February","March","April","May","June",
"July","August","September","October","November","December"]);
this.selectedChoice = ko.observable();
this.selectedChoice.subscribe(function(newValue) {
myMonth = this.choices.indexOf(this.selectedChoice());
myLayerGroup.clearLayers();
myLayerGroup.addLayer(myLayers[myMonth]);
console.log(myMonth); //works!
return myMonth; // no effect?!
},this);
};
ko.applyBindings(new viewModel());
// popUp window content
function onEachFeature(feature, layer) {
if (feature.properties) {
var popupContent = "Selected month: "+ myMonth;
layer.bindPopup(popupContent);
}
};
我在您的代碼中看到的唯一問題是該語句
return myMonth; // no effect?!
絕對沒有任何作用,因為它在.subscribe函數內部沒有任何意義。 無法將值返回給 。
這是一個小提琴,顯示您的代碼幾乎按原樣工作,因此我不清楚您遇到的實際問題。 是否有錯誤消息? 您如何致電onEachFeature
?
編輯1:現在,有了您更新的小提琴,我看到的問題是,您的popupContent從一開始就被設置了一次,之后再也沒有更新。 geoJSON函數立即調用您的onEachFeature函數以獲取所選圖層的內容(當時該內容尚未定義),並將其永久存儲為其內容。
popupContent似乎也希望使用扁平字符串,因此可能沒有任何方法可以使它以剔除綁定方式動態更新。 我認為,只要數據更改,您都必須通過再次調用geoJSON來重新創建該層。
這是一個更新的小提琴,我在其中將您的geoJSON調用移到了createLayer函數中,以便訂閱可以調用它來重建圖層:
this.selectedChoice.subscribe(function(newValue) {
myMonth = this.choices.indexOf(this.selectedChoice());
myLayerGroup.clearLayers();
myLayerGroup.addLayer(createLayer(myLayers[myMonth]));
}, this);
您所謂的全局變量實際上是window對象的屬性(例如,請參見此SO帖子 )。
此評論:
// popUp window content
function onEachFeature(feature, layer) {
if (feature.properties) {
var popupContent = "Selected month: "+ myMonth;
layer.bindPopup(popupContent);
}
};
讓我認為您正在嘗試從myMonth
出窗口訪問父窗口中定義的變量myMonth
,這種方式是不可能的。
您可以使用window.opener.myMonth
語法訪問該變量,如本文檔所述 。
// popUp window content
function onEachFeature(feature, layer) {
if (feature.properties && window.opener) {
var popupContent = "Selected month: "+ window.opener.myMonth;
layer.bindPopup(popupContent);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.