z_av
z_av

Reputation: 83

Backbone.js- Scope of 'this' in a Model method

I have a problem with the scope of 'this' when defining a Backbone model. In the function updateGeoLocation I'm calling an anonymous function that handles the update of the location and placement of the marker.

The problem is that when inside the anonymous function 'this' refer to the window instead of the model. I tried to add this to my init function but it still doesn't solve the problem:

 _.bindAll(this , 'updateGeoLocation'); 

The code is:

var googleMapsModel = Backbone.Model.extend ({


    //Init map according to the window height
    initialize: function () {
        _.bindAll(this , 'updateGeoLocation');
        this.set('currentLocation', new google.maps.LatLng(-34.397, 150.644));
        $("#map-content").height(this.getRealContentHeight());
        var mapOptions = {
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
        this.updateGeoLocation();
    },
    //Update geo location and place marker on the map
    updateGeoLocation: function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                lat = position.coords.latitude;
                long = position.coords.longitude;
                console.log (lat);
                console.log((long));
                currentLocation = new google.maps.LatLng(lat,long);
                map.setCenter(currentLocation);
                //update marker
                this.updateCurrentLocationMarker(currentLocation);
            }) , function() {
                alert("no Geo Location");
            };
        }
    },
updateCurrentLocationMarker: function (markerLocation) {
        myLocationMarker = new google.maps.Marker({
            position: markerLocation,
            map: map
        });
        this.model.set('currentLocationMarker', myLocationMarker);
    },

Any help will be appriciated

Upvotes: 1

Views: 677

Answers (1)

Cyril N.
Cyril N.

Reputation: 39859

Replace your updateGeoLocation method by that :

updateGeoLocation: function () {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(_.bind(function (position) {
            lat = position.coords.latitude;
            long = position.coords.longitude;
            console.log (lat);
            console.log((long));
            currentLocation = new google.maps.LatLng(lat,long);
            map.setCenter(currentLocation);
            //update marker
            this.updateCurrentLocationMarker(currentLocation);
        }, this)) , function() {
            alert("no Geo Location");
        };
    }
},

The key here is _.bind, take a look at the doc

Upvotes: 1

Related Questions