deps-parser.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var Emitter = require('emitter'),
  2. observer = new Emitter()
  3. /*
  4. * Auto-extract the dependencies of a computed property
  5. * by recording the getters triggered when evaluating it.
  6. *
  7. * However, the first pass will contain duplicate dependencies
  8. * for computed properties. It is therefore necessary to do a
  9. * second pass in injectDeps()
  10. */
  11. function catchDeps (binding) {
  12. observer.on('get', function (dep) {
  13. binding.dependencies.push(dep)
  14. })
  15. binding.value.get()
  16. observer.off('get')
  17. }
  18. /*
  19. * The second pass of dependency extraction.
  20. * Only include dependencies that don't have dependencies themselves.
  21. */
  22. function injectDeps (binding) {
  23. binding.dependencies.forEach(function (dep) {
  24. if (!dep.dependencies.length) {
  25. dep.dependents.push.apply(dep.dependents, binding.instances)
  26. }
  27. })
  28. }
  29. module.exports = {
  30. /*
  31. * the observer that catches events triggered by getters
  32. */
  33. observer: observer,
  34. /*
  35. * parse a list of computed property bindings
  36. */
  37. parse: function (bindings) {
  38. observer.isObserving = true
  39. bindings.forEach(catchDeps)
  40. bindings.forEach(injectDeps)
  41. observer.isObserving = false
  42. }
  43. }