maintaining scope inside a jquery ui widget

345 views Asked by At

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…}
2

There are 2 answers

0
actual_kangaroo On BEST ANSWER

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));
2
actual_kangaroo On

EDIT: this answer does address rebinding caused by the event handler

var that is scoped inside the _create function, you should be able to access this from within initialize.

new google.maps.LatLng(this.options.centerLat, this.options.centerLong)

check out this similar question about "this"