Skip to content

Instantly share code, notes, and snippets.

@nara-l
Created June 1, 2018 01:46
Show Gist options
  • Save nara-l/baf1924cf9058883c1d936af2a5dd116 to your computer and use it in GitHub Desktop.
Save nara-l/baf1924cf9058883c1d936af2a5dd116 to your computer and use it in GitHub Desktop.
Understanding JS scope in promise call back: Update Vuejs property in promise call back (capturing 'this' in closure )
/*
* There are about 2 ways to do tis
*/
import firebase from 'firebase'
export default {
name: "SignUp",
data: () => ({
successAlert: false,
errorAlert: false,
email: '',
password: ''
}),
methods: {
// METHOD 1
signup: function() {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
function(user){
this.successAlert = true
}.bind(this), // same here
function(err){
this.errorAlert = true
}.bind(this) //capture 'this' in closure to allow variables in and out of promise
// without binding, you get error: Uncaught TypeError: Cannot set property 'errorAlert' of undefined
)
},
// METHOD 2, introducing self
signup: function() {
var self = this
firebase.auth().createUserWithEmailAndPassword(this.email, this.password).then(
function(user){
self.successAlert = true
}
function(err){
self.errorAlert = true
}
)
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment