Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js binding this to success/error callbacks?

I have the following code in my Backbone app, Is there a way to bind "this" to the callbacks rather than having to assign "$this" all the time?

addItem: function()
{
    var $this = this;

    (new Project()).save({name:$('#project_name').val()},{
        success:function(model, response)
        {
            $this.collection.add(model);
        },
        error: function()
        {
            console.log('wtf');
        }
   });
}
like image 442
Rob Avatar asked Jan 17 '23 07:01

Rob


1 Answers

You have Underscore available so you could _.bind manually:

(new Project()).save({ name: $('#project_name').val() }, {
    success: _.bind(function(model, response) {
        this.collection.add(model);
    }, this),
    error: _.bind(function() {
        console.log('wtf');
    }, this)
});

Or just use methods for the callbacks and _.bind or _.bindAll those:

initialize: function() {
    _.bindAll(this, 'success_callback', 'error_callback');
},
success_callback: function(model, response) {
    this.collection.add(model);
},
error_callback: function() {
    console.log('WTF?');
},
addItem: function() {
    (new Project()).save({ name: $('#project_name').val() }, {
        success: this.success_callback,
        error:   this.error_callback
    });
}
like image 163
mu is too short Avatar answered Jan 18 '23 22:01

mu is too short