0

I do this in a dirty way, wondering if there's a nicer way:

this.collection.create(
    {
        'name': this.$('.name').val()
    },
    {
        success: function() {
            alert(_this);
        },
        error: function() {
            alert(_this);
        },
        wait: true
    }
);
Mihai Vinaga
  • 1,059
  • 2
  • 10
  • 27

2 Answers2

1

I'll assume you've set var _this = this; somewhere but just forgot to include it.

What you can do is to use Function.prototype.bind (EcmaScript 5) to bind the success and error callbacks to the right context.

success: function() {
    alert(this);
}.bind(this),

error: function() {
    alert(this);
}.bind(this),

That's supported in IE9 and up.

(If for some reason you're supporting IE8 there's a polyfill on the MDN page)

ivarni
  • 17,658
  • 17
  • 76
  • 92
1

With latest backbonejs you could pass context via options by using context keyword and don't use any polyfills at all :

this.collection.create(
    {
        'name': this.$('.name').val()
    },
    {
        success: function() {
            alert(this);
        },
        error: function() {
            alert(this);
        },
        context: this,
        wait: true
    }
);