我有一个下拉菜单,允许用户选择特定月份。可观察数组根据用户选择更改我的传单 map 的图层(工作完美)。
现在我需要另一个函数的选择值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 函数内部没有任何意义。没有地方可以将值返回到。
这是一个fiddle显示您的代码几乎按原样工作,所以我不清楚您遇到的实际问题。有错误信息吗?您如何调用onEachFeature
?
编辑1: 通过您更新的 fiddle ,我现在可以看到问题是您的 popupContent 一开始就被设置了一次,之后就不再更新了。 geoJSON 函数立即调用您的 onEachFeature 函数来获取所选图层的内容(当时尚未定义),并将其永久存储为其内容。
popupContent 似乎也需要一个扁平字符串,因此可能没有任何方法可以使其以 knockout 绑定(bind)方式动态更新。我认为只要数据发生变化,您就必须通过再次调用 geoJSON 来重新创建图层。
这是一个更新的 fiddle ,我将 geoJSON 调用移动到 createLayer 函数中,以便订阅调用它来重建图层:
this.selectedChoice.subscribe(function(newValue) {
myMonth = this.choices.indexOf(this.selectedChoice());
myLayerGroup.clearLayers();
myLayerGroup.addLayer(createLayer(myLayers[myMonth]));
}, this);
关于javascript - 在外部函数中 knockout 可观察数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42513280/