jqueryjquery-uijquery-ui-widget-factoryjquery-ui-widget

maintaining scope inside a jquery ui widget


I am having a problem with loosing scope inside a widget. Inside _initialize, this.options does not work, and neither does that.options. How can I access the scope of the widget from this method?

$.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,
            };

To clarify

$.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

does not work, when I console.log this in _initialize I get

Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

Solution

  • google.maps.event.addDomListener changes what this refers to. you can change it back by calling the bind mehtod

    google.maps.event.addDomListener(window, 'load', this._initialize.bind(this));