Cof*_*fey 7 javascript jquery google-maps browserify gulp
我正在使用Gulp和Browserify捆绑我的JavaScripts.我需要公开一个应该在加载Google Maps API后执行的回调函数.
如果不使用类似的东西window.initMap怎么办呢?这个问题是我需要在initMap中触发大量其他方法,因此除了使用window.functionName和污染全局命名空间之外,还必须有更好的方法.
另一方面,只是排除callback参数并做这样的事情是否可以?
$.getScript('https://maps.googleapis.com/maps/api/js').done(function() {
initMap();
});
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.我花了更多的时间来承认让它发挥作用.
gulpfile.js:
gulp.task('browserify', ['eslint'], function() {
return browserify('/src/js/main.js')
.bundle()
.pipe(source('main.js'))
.pipe(buffer())
.pipe(gulp.dest('/dist/js'))
.pipe(reload({ stream: true }));
});
Run Code Online (Sandbox Code Playgroud)
main.js:
require('jquery');
require('./map');
Run Code Online (Sandbox Code Playgroud)
map.js:
var map = (function() {
'use strict';
var mapElement = $('#map');
function googleMapsAPI() {
$.getScript('https://maps.googleapis.com/maps/api/js?callback=initMap');
}
function initMap() {
var theMap = new google.maps.Map(mapElement);
// functions...
}
function init() {
googleMapsAPI();
}
});
map.init();
Run Code Online (Sandbox Code Playgroud)
不,不包含callback参数是不行的。
谷歌地图 API 库调用一堆其他脚本加载到页面上,然后,当它们全部加载完毕后,callback在窗口对象上调用参数。
只需在对象上声明它window:
var MyApp = {
init: function() {
//all your stuff
}
}
window.initMap = function() {
window.initMap = null; //set this to null this so that it can't get called anymore....if you want
MyApp.init();
};
Run Code Online (Sandbox Code Playgroud)
然后只需在页面上包含脚本标记即可:
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1798 次 |
| 最近记录: |