Last active
December 16, 2015 00:49
-
-
Save jakcharlton/5350863 to your computer and use it in GitHub Desktop.
Assigning "this" for use inside a closure ... which reads/scans better
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// using self - this seems the most obvious, esp coming from Rails | |
var self = this; | |
this.create({ | |
myModel: { | |
email: $('#email').val() | |
} | |
}, | |
{ | |
wait: true, | |
success: function (responseModel, resp) { | |
self.$('.modal-family-invite').modal('hide'); | |
} | |
} | |
// Using scope | |
var scope = this; | |
this.create({ | |
myModel: { | |
email: $('#email').val() | |
} | |
}, | |
{ | |
wait: true, | |
success: function (responseModel, resp) { | |
scope.$('.modal-family-invite').modal('hide'); | |
} | |
} | |
// using that | |
// this keeps confusing me as I see "that" inside a view as refering to "something else" | |
var that = this; | |
this.create({ | |
myModel: { | |
email: $('#email').val() | |
} | |
}, | |
{ | |
wait: true, | |
success: function (responseModel, resp) { | |
that.$('.modal-family-invite').modal('hide'); | |
} | |
} | |
// Using Underscore .bind | |
(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 | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment