binding.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Binding class.
  3. *
  4. * each property on the viewmodel has one corresponding Binding object
  5. * which has multiple directive instances on the DOM
  6. * and multiple computed property dependents
  7. */
  8. function Binding (compiler, key, isExp) {
  9. this.value = undefined
  10. this.isExp = !!isExp
  11. this.root = !this.isExp && key.indexOf('.') === -1
  12. this.compiler = compiler
  13. this.key = key
  14. this.instances = []
  15. this.subs = []
  16. this.deps = []
  17. }
  18. var BindingProto = Binding.prototype
  19. /**
  20. * Process the value, then trigger updates on all dependents
  21. */
  22. BindingProto.update = function (value) {
  23. this.value = value
  24. var i = this.instances.length
  25. while (i--) {
  26. this.instances[i].update(value)
  27. }
  28. this.pub()
  29. }
  30. /**
  31. * -- computed property only --
  32. * Force all instances to re-evaluate themselves
  33. */
  34. BindingProto.refresh = function () {
  35. var i = this.instances.length
  36. while (i--) {
  37. this.instances[i].refresh()
  38. }
  39. this.pub()
  40. }
  41. /**
  42. * Notify computed properties that depend on this binding
  43. * to update themselves
  44. */
  45. BindingProto.pub = function () {
  46. var i = this.subs.length
  47. while (i--) {
  48. this.subs[i].refresh()
  49. }
  50. }
  51. /**
  52. * Unbind the binding, remove itself from all of its dependencies
  53. */
  54. BindingProto.unbind = function () {
  55. var i = this.instances.length
  56. while (i--) {
  57. this.instances[i].unbind()
  58. }
  59. i = this.deps.length
  60. var subs
  61. while (i--) {
  62. subs = this.deps[i].subs
  63. subs.splice(subs.indexOf(this), 1)
  64. }
  65. }
  66. module.exports = Binding