open.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var Gun = (typeof window !== "undefined")? window.Gun : require('../gun');
  2. Gun.chain.open = function(cb, opt, at){
  3. opt = opt || {};
  4. opt.doc = opt.doc || {};
  5. opt.ids = opt.ids || {};
  6. opt.any = opt.any || cb;
  7. opt.meta = opt.meta || false;
  8. opt.ev = opt.ev || {off: function(){
  9. Gun.obj.map(opt.ev.s, function(e){
  10. if(e){ e.off() }
  11. });
  12. opt.ev.s = {};
  13. }, s:{}}
  14. return this.on(function(data, key, ctx, ev){
  15. if(opt.meta !== true){
  16. delete ((data = Gun.obj.copy(data))||{})._;
  17. }
  18. clearTimeout(opt.to);
  19. opt.to = setTimeout(function(){
  20. if(!opt.any){ return }
  21. opt.any.call(opt.at.$, opt.doc, opt.key, opt, opt.ev);
  22. if(opt.off){
  23. opt.ev.off();
  24. opt.any = null;
  25. }
  26. }, opt.wait || 1);
  27. opt.at = opt.at || ctx;
  28. opt.key = opt.key || key;
  29. opt.ev.s[this._.id] = ev;
  30. if(Gun.val.is(data)){
  31. if(!at){
  32. opt.doc = data;
  33. } else {
  34. at[key] = data;
  35. }
  36. return;
  37. }
  38. var tmp = this, id;
  39. Gun.obj.map(data, function(val, key){
  40. var doc = at || opt.doc;
  41. if (!doc) {
  42. return;
  43. }
  44. if(!(id = Gun.val.link.is(val))){
  45. doc[key] = val;
  46. return;
  47. }
  48. if(opt.ids[id]){
  49. doc[key] = opt.ids[id];
  50. return;
  51. }
  52. tmp.get(key).open(opt.any, opt, opt.ids[id] = doc[key] = {});
  53. });
  54. })
  55. }