【发布时间】:2014-07-13 13:37:03
【问题描述】:
我正在尝试异步生成 Google 地图。那里有很多示例,但找到的示例使用 global(?) 函数来展示使用回调函数的概念。然而,我正在处理的项目定义了各种对象并使用原型向它们添加属性/功能。相关源码如下:
var Demo = new Array();
Demo.Content = function() { };
Demo.Content.prototype = { };
Demo.Content.Controller = function() {
this.contentView = new Demo.Content.View(this);
};
Demo.Content.Controller.prototype = {
initialize : function() {
this.contentView.initialize();
},
onGoogleMapsScriptLoaded : function() {
alert('onGoogleMapsScriptLoaded');
},
};
Demo.Content.View = function(controller) {
this.controller = controller;
};
Demo.Content.View.prototype = {
initialize : function() {
// now called from background script (Chrome extensions)
//this.asyncLoadGoogleMap();
},
asyncLoadGoogleMap : function() {
$.getScript("http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=???")
.done(function (script, textStatus) {
alert("Google map script loaded successfully");
})
.fail(function (jqxhr, settings, ex) {
alert("Could not load Google Map script: " + ex);
});
},
};
contentController = new Demo.Content.Controller();
contentController.initialize();
虽然我收到成功消息“Google 地图脚本已成功加载”,但我不知道将什么用作回调函数——总是undefined。例如,我尝试了contentController.test -- Cannot read property 'onGoogleMapsScriptLoaded' of undefined -- 或者确实使用了 Web 上的示例中的全局函数。如何设置回调函数?还是我这里有一个更根本的错误?
编辑: 整个内容是 Google Chrome 扩展内容脚本的一部分——以防万一这很重要。这包括我现在在页面真正完成加载时加载地图
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.sendMessage(tabId, {action: 'load-map'}, function(){});
}
});
在后台脚本中。内容脚本有一个调用asyncLoadGoogleMap 的消息侦听器。所以页面应该完全在那里。尽管如此,我还是遇到了同样的错误。
【问题讨论】:
-
问题似乎是我在 Chrome 扩展的内容脚本中尝试这个。当我使用来自Google Developer Page 的基本示例时——它作为“独立”页面运行得非常好——在我的内容脚本中,我收到回调函数未定义的错误。但我不知道问题可能是什么。
标签: javascript google-maps asynchronous callback