Search code examples
javascriptbackbone.jsmarionette

Change "this" scope for backbone collection.create


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
    }
);

Solution

  • 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)