gpt4 book ai didi

Javascript 对象字面范围问题?

转载 作者:行者123 更新时间:2023-11-28 16:18:44 26 4
gpt4 key购买 nike

我很难理解为什么 this.$mapthis.markers 未定义。这是我正在使用的代码,并且我在我希望这些变量提供值的地方添加了注释:

(function($) {
'use strict';

var A = {

/**
* Initialize the A object
*/
init: function() {
this.$map = this.renderMap();
this.markers = this.getMarkers();

this.renderMarkers();
},

renderMap: function() {

var url = 'http://a.tiles.mapbox.com/v3/delewis.map-i3eukewg.jsonp';

// Get metadata about the map from MapBox
wax.tilejson(url, function(tilejson) {
var map = new L.Map('map', {zoomControl: false});

var ma = new L.LatLng(42.2625, -71.8028);

map.setView(ma, 8);

// Add MapBox Streets as a base layer
map.addLayer(new wax.leaf.connector(tilejson));

return function() {
return map;
};
});
},

renderMarkers: function() {
var geojsonLayer = new L.GeoJSON(null, {
pointToLayer: function (latlng){
return new L.CircleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
});
}
});

geojsonLayer.addGeoJSON(this.markers); // this.markers is undefined
this.$map.addLayer(geojsonLayer); // this.$map is undefined

},

getMarkers: function() {
$.getJSON("/geojson/", function (data) {
return data;
});
}
};

/**
* A interactions
*/
$(document).ready(function() {
A.init()
});

})(jQuery.noConflict());

我花了一天的大部分时间进行搜索,我认为我在这里遗漏了一些基本的东西,但我不明白。

最佳答案

renderMapgetMarkers 方法都不会返回任何值,因此它们的返回值是未定义

看起来您正在尝试从 ajax 请求初始化这些字段,这不一定是个好主意。

你可能应该做的是:

getMarkers: function(callback){
var result = this;
$.getJSON("url", function(jsonData){
result.markers = jsonData;
if(callback) callback()
});
},

当对象的字段可用时,它将延迟初始化它们。

注意:AJAX 是异步,您不能依赖此回调来快速设置成员,甚至永远不能(它可能会失败)。这表明您需要更多地考虑您的设计,并尝试更多地使用回调。

例如如上所述修改 getMarkersrenderMap 函数以获取存储数据后调用的回调,然后将 init 更改为:

init: function(){
var res = this;
var post_init_callback = function(){
if(res.$map != undefined && res.markers!=undefined){
//this will only run after both ajax calls are complete
res.renderMarkers();
}
};
this.getMarkers(post_init_callback);
this.renderMap(post_init_callback);
},

关于Javascript 对象字面范围问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10526384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com