vue2/examples/firebase/app.js

75 lines
1.5 KiB
JavaScript
Raw Normal View History

2014-09-24 09:06:32 +08:00
var baseURL = 'https://vue-demo.firebaseIO.com/'
var emailRE = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
/**
* Setup firebase sync
*/
var Users = new Firebase(baseURL + 'users')
Users.on('child_added', function (snapshot) {
var item = snapshot.val()
2015-08-03 00:04:56 +08:00
item.id = snapshot.key()
2014-09-24 09:06:32 +08:00
app.users.push(item)
})
Users.on('child_removed', function (snapshot) {
2015-08-03 00:04:56 +08:00
var id = snapshot.key()
2014-09-24 09:06:32 +08:00
app.users.some(function (user) {
if (user.id === id) {
app.users.$remove(user)
return true
}
})
})
/**
* Create Vue app
*/
var app = new Vue({
// element to mount to
el: '#app',
// initial data
data: {
users: [],
newUser: {
name: '',
email: ''
}
},
// computed property for form validation state
computed: {
2015-08-03 00:04:56 +08:00
validation: function () {
return {
name: !!this.newUser.name.trim(),
email: emailRE.test(this.newUser.email)
2014-09-24 09:06:32 +08:00
}
2015-08-03 00:04:56 +08:00
},
isValid: function () {
var validation = this.validation
return Object.keys(validation).every(function (key) {
return validation[key]
})
2014-09-24 09:06:32 +08:00
}
},
2015-08-03 00:04:56 +08:00
2014-09-24 09:06:32 +08:00
// methods
methods: {
addUser: function (e) {
e.preventDefault()
if (this.isValid) {
Users.push(this.newUser)
2015-08-03 00:04:56 +08:00
this.newUser.name = ''
this.newUser.email = ''
2014-09-24 09:06:32 +08:00
}
},
removeUser: function (user) {
new Firebase(baseURL + 'users/' + user.id).remove()
}
}
2015-08-03 00:04:56 +08:00
})