app.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. var baseURL = 'https://vue-demo.firebaseIO.com/'
  2. 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,}))$/
  3. /**
  4. * Setup firebase sync
  5. */
  6. var Users = new Firebase(baseURL + 'users')
  7. Users.on('child_added', function (snapshot) {
  8. var item = snapshot.val()
  9. item.id = snapshot.name()
  10. app.users.push(item)
  11. })
  12. Users.on('child_removed', function (snapshot) {
  13. var id = snapshot.name()
  14. app.users.some(function (user) {
  15. if (user.id === id) {
  16. app.users.$remove(user)
  17. return true
  18. }
  19. })
  20. })
  21. /**
  22. * Create Vue app
  23. */
  24. var app = new Vue({
  25. // element to mount to
  26. el: '#app',
  27. // initial data
  28. data: {
  29. users: [],
  30. newUser: {
  31. name: '',
  32. email: ''
  33. },
  34. validation: {
  35. name: false,
  36. email: false
  37. }
  38. },
  39. // validation filters are "write only" filters
  40. filters: {
  41. nameValidator: {
  42. write: function (val) {
  43. this.validation.name = !!val
  44. return val
  45. }
  46. },
  47. emailValidator: {
  48. write: function (val) {
  49. this.validation.email = emailRE.test(val)
  50. return val
  51. }
  52. }
  53. },
  54. // computed property for form validation state
  55. computed: {
  56. isValid: function () {
  57. var valid = true
  58. for (var key in this.validation) {
  59. if (!this.validation[key]) {
  60. valid = false
  61. }
  62. }
  63. return valid
  64. }
  65. },
  66. // methods
  67. methods: {
  68. addUser: function (e) {
  69. e.preventDefault()
  70. if (this.isValid) {
  71. Users.push(this.newUser)
  72. this.newUser = {
  73. name: '',
  74. email: ''
  75. }
  76. }
  77. },
  78. removeUser: function (user) {
  79. new Firebase(baseURL + 'users/' + user.id).remove()
  80. }
  81. }
  82. })