Backbone.js binding this to success/error callbacks?
backbone.js, bind, jquery, underscore.js
Solution
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
});
}
Problem
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'); } }); } ```