我在widget内失去范围时遇到问题。在_initialize内部,this.options
不起作用,that.options
也不起作用。如何从此方法访问窗口小部件的范围?
$.widget("myproj.map", {
options: {
centerLat: 51.511214,
centerLong: -0.119824,
},
// the constructor
_create: function () {
var that = this;
google.maps.event.addDomListener(window, 'load', this._initialize);
},
_initialize: function () {
var mapOptions = {
center: new google.maps.LatLng(that.options.centerLat, that.options.centerLong),
zoom: 11,
};
澄清
$.widget("myproj.map", {
options: {
centerLat: 51.511214,
centerLong: -0.119824,
},
// the constructor
_create: function () {
google.maps.event.addDomListener(window, 'load', this._initialize);
},
_initialize: function () {
console.log(this);
var mapOptions = {
center: new google.maps.LatLng(this.options.centerLat, this.options.centerLong),
zoom: 11
}; ...code omitted
不起作用,当我在_initialize中控制.log时,我得到
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
答案 0 :(得分:1)
google.maps.event.addDomListener
更改了this
所指的内容。您可以致电bind mehtod
google.maps.event.addDomListener(window, 'load', this._initialize.bind(this));
答案 1 :(得分:0)
编辑:这个答案确实解决了由事件处理程序引起的重新绑定
var that
的范围是_create
功能,您应该可以访问this
from within initialize。
new google.maps.LatLng(this.options.centerLat, this.options.centerLong)