在jquery ui小部件中维护范围

时间:2013-12-05 00:23:11

标签: jquery jquery-ui jquery-ui-widget-factory jquery-ui-widget

我在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…}

2 个答案:

答案 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)

查看此similar question about "this"