jxu
jxu

Reputation: 50

Is there a better way to pass "this" object to a callback function?

I am new to backbonejs. I am trying to pass the correct this object to a callback function where that function is a method of the view.

My current solution:

APP.LocationFormView = APP.View.extend({
    initialize: function () {    
        if (navigator.geolocation) {
            var that = this;

            var success = function(position) {
                _.bind(that.onSuccessUpdatePos, that, position)();
            };

            var error = function(error) {
                _.bind(that.onFailUpdatePos, that, error)();
            }

            navigator.geolocation.getCurrentPosition(success, 
                                                     error);
        } else {

        }
    },

    onSuccessUpdatePos: function(position) {
        // We can access "this" now
    },

    onFailUpdatePos : function(error) {
        // We can access "this" now
    }
});

Is this a correct way to achieve what I want? Is there any less verbose solution for this?

Upvotes: 2

Views: 462

Answers (2)

abraham
abraham

Reputation: 47833

This is how I would do it. One nice aspect of bindAll is that if you add additional functions to LocationFormView they will automatically have this bound.

APP.LocationFormView = APP.View.extend({
    initialize: function () {   
        _.bindAll(this); 
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(this.onSuccessUpdatePos, 
                                                     this.onFailUpdatePos);
        } else {

        }
    },

    onSuccessUpdatePos: function(position) {
        // We can access "this" now
    },

    onFailUpdatePos : function(error) {
        // We can access "this" now
    }
});

Upvotes: 5

Ry-
Ry-

Reputation: 224904

_.bind is for later binding. What you would normally do is this:

that.onSuccessUpdatePos(position); // that is already the context

But instead, you can just pass it directly:

var success = _.bind(that.onSuccessUpdatePos, that, position);
var error   = _.bind(that.onFailUpdatePos, that, error);

navigator.geolocation.getCurrentPosition(success, error);

That is, if that feels more clear to you than the "manual" solution.

Upvotes: 2

Related Questions