0

So I already know a way around this, but I'm curious if there is a better way to handle this call. I should further mention that I'm using Backbone. Here is what I'm trying to accomplish:

loadKey: function() {
    $.ajax({
        // some settings
        success: function(data) {
            this.set('key', data.key);
        }
    });
}

Now obviously this example won't work, because the nested success function is out of the scope of the models this. Here is how I'm currently handling this:

loadKey: function() {
    self = this;
    $.ajax({
        // some settings
        success: function(data) {
            self.set('key', data.key);
        }
    });
}

So back to my question. Is this a perfectly acceptable way to handle this? Or is there another way to do this that's considered better?

Joshua
  • 1,260
  • 3
  • 17
  • 33

1 Answers1

0

Try to use bind from underscore to bind this context when exec the func.

loadKey: function() {
    $.ajax({
        // some settings
        success: _.bind(function(data) {
            this.set('key', data.key);
        }, this)
    });
}

Updated More discussions on the topics of that=this or self=this:

Community
  • 1
  • 1
Ming Chan
  • 1,938
  • 11
  • 21
  • Is there any reason for doing is this particular way over setting a variable to this? Like my example of setting this to the variable self. – Joshua Jul 15 '13 at 03:20
  • I use _.bind but you should read through the discussions and make your own call. – Ming Chan Jul 15 '13 at 03:43
  • Thanks, that's very useful information. I didn't find those discussions in my searching. – Joshua Jul 15 '13 at 04:30