Skip to content

Instantly share code, notes, and snippets.

@jakcharlton
Last active December 16, 2015 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakcharlton/5350863 to your computer and use it in GitHub Desktop.
Save jakcharlton/5350863 to your computer and use it in GitHub Desktop.
Assigning "this" for use inside a closure ... which reads/scans better
// 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