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');
}
});
}
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
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With