lifecycle.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var _ = require('../util')
  2. /**
  3. * Set instance target element and kick off the compilation
  4. * process. The passed in `el` can be a selector string, an
  5. * existing Element, or a DocumentFragment (for block
  6. * instances).
  7. *
  8. * @param {Element|DocumentFragment|string} el
  9. * @public
  10. */
  11. exports.$mount = function (el) {
  12. if (this._isCompiled) {
  13. _.warn('$mount() should be called only once.')
  14. return
  15. }
  16. this._callHook('beforeCompile')
  17. this._initElement(el)
  18. this._compile()
  19. this._isCompiled = true
  20. this._callHook('compiled')
  21. this.$once('hook:attached', function () {
  22. this._isAttached = true
  23. this._isReady = true
  24. this._callHook('ready')
  25. this._initDOMHooks()
  26. })
  27. if (_.inDoc(this.$el)) {
  28. this._callHook('attached')
  29. }
  30. }
  31. /**
  32. * Teardown an instance, unobserves the data, unbind all the
  33. * directives, turn off all the event listeners, etc.
  34. *
  35. * @param {Boolean} remove - whether to remove the DOM node.
  36. * @public
  37. */
  38. exports.$destroy = function (remove) {
  39. if (this._isDestroyed) {
  40. return
  41. }
  42. this._callHook('beforeDestroy')
  43. // remove DOM element
  44. if (remove) {
  45. if (this.$el === document.body) {
  46. this.$el.innerHTML = ''
  47. } else {
  48. this.$remove()
  49. }
  50. }
  51. var i
  52. // remove self from parent. only necessary
  53. // if this is called by the user.
  54. var parent = this.$parent
  55. if (parent && !parent._isDestroyed) {
  56. i = parent._children.indexOf(this)
  57. parent._children.splice(i)
  58. }
  59. // destroy all children.
  60. i = this._children.length
  61. while (i--) {
  62. this._children[i].$destroy()
  63. }
  64. // teardown data/scope
  65. this._teardownScope()
  66. // teardown all user watchers
  67. for (var id in this._watchers) {
  68. this.$unwatch(id)
  69. }
  70. // teardown all directives
  71. i = this._directives.length
  72. while (i--) {
  73. this._directives[i]._teardown()
  74. }
  75. // clean up
  76. this._children =
  77. this._watchers =
  78. this._activeWatcher =
  79. this.$el =
  80. this.$el.__vue__ =
  81. this._directives = null
  82. // call the last hook...
  83. this._isDestroyed = true
  84. this._callHook('afterDestroy')
  85. // turn off all instance listeners.
  86. this._emitter.off()
  87. }