vuepouch.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var init = function(){
  2. var bindings = this.$options.pouchdb
  3. ensureRef(this)
  4. for(var key in bindings) {
  5. bind(this,key,bindings[key])
  6. }
  7. }
  8. function ensureRef (vm) {
  9. if (!vm.$pouchdbRefs) {
  10. vm.$pouchdbRefs = Object.create(null)
  11. }
  12. }
  13. function defineReactive(vm,key,val){
  14. if(key in vm){
  15. vm[key] = val
  16. } else {
  17. Vue.util.defineReactive(vm,key,val)
  18. }
  19. }
  20. function bind(vm,key,source){
  21. var array = []
  22. defineReactive(vm,key,array)
  23. vm.$pouchdbRefs[key] = source
  24. source.changes({
  25. since:'now',
  26. live: true,
  27. include_docs: true
  28. }).on('complete',function(info){
  29. }).on('change',function(change){
  30. vm[key].push(change.doc)
  31. }).on('err',function(err){
  32. })
  33. source.allDocs({
  34. include_docs: true,
  35. descending: true
  36. }).then(function(doc){
  37. var docs = doc.rows.map(function(obj){
  38. return obj.doc
  39. })
  40. defineReactive(vm,key,docs)
  41. }).catch(function(err){
  42. })
  43. }
  44. var PouchMixin = {
  45. init: init, // making it usable with vuejs 1.x.x
  46. beforeCreate: init
  47. }
  48. function install(Vue){
  49. Vue.mixin(PouchMixin)
  50. }
  51. // auto install
  52. if (typeof window !== 'undefined' && window.Vue) {
  53. install(window.Vue)
  54. }