watcher.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. var _ = require('./util')
  2. var config = require('./config')
  3. var Dep = require('./observer/dep')
  4. var expParser = require('./parsers/expression')
  5. var batcher = require('./batcher')
  6. var uid = 0
  7. /**
  8. * A watcher parses an expression, collects dependencies,
  9. * and fires callback when the expression value changes.
  10. * This is used for both the $watch() api and directives.
  11. *
  12. * @param {Vue} vm
  13. * @param {String} expression
  14. * @param {Function} cb
  15. * @param {Object} options
  16. * - {Array} filters
  17. * - {Boolean} twoWay
  18. * - {Boolean} deep
  19. * - {Boolean} user
  20. * - {Boolean} sync
  21. * - {Boolean} lazy
  22. * - {Function} [preProcess]
  23. * @constructor
  24. */
  25. function Watcher (vm, expOrFn, cb, options) {
  26. // mix in options
  27. if (options) {
  28. _.extend(this, options)
  29. }
  30. var isFn = typeof expOrFn === 'function'
  31. this.vm = vm
  32. vm._watchers.push(this)
  33. this.expression = isFn ? expOrFn.toString() : expOrFn
  34. this.cb = cb
  35. this.id = ++uid // uid for batching
  36. this.active = true
  37. this.dirty = this.lazy // for lazy watchers
  38. this.deps = []
  39. this.newDeps = null
  40. this.prevError = null // for async error stacks
  41. // parse expression for getter/setter
  42. if (isFn) {
  43. this.getter = expOrFn
  44. this.setter = undefined
  45. } else {
  46. var res = expParser.parse(expOrFn, this.twoWay)
  47. this.getter = res.get
  48. this.setter = res.set
  49. }
  50. this.value = this.lazy
  51. ? undefined
  52. : this.get()
  53. // state for avoiding false triggers for deep and Array
  54. // watchers during vm._digest()
  55. this.queued = this.shallow = false
  56. }
  57. /**
  58. * Add a dependency to this directive.
  59. *
  60. * @param {Dep} dep
  61. */
  62. Watcher.prototype.addDep = function (dep) {
  63. var newDeps = this.newDeps
  64. var old = this.deps
  65. if (_.indexOf(newDeps, dep) < 0) {
  66. newDeps.push(dep)
  67. var i = _.indexOf(old, dep)
  68. if (i < 0) {
  69. dep.addSub(this)
  70. } else {
  71. old[i] = null
  72. }
  73. }
  74. }
  75. /**
  76. * Evaluate the getter, and re-collect dependencies.
  77. */
  78. Watcher.prototype.get = function () {
  79. this.beforeGet()
  80. var vm = this.vm
  81. var value
  82. try {
  83. value = this.getter.call(vm, vm)
  84. } catch (e) {
  85. if (
  86. process.env.NODE_ENV !== 'production' &&
  87. config.warnExpressionErrors
  88. ) {
  89. _.warn(
  90. 'Error when evaluating expression "' +
  91. this.expression + '". ' +
  92. (config.debug
  93. ? '' :
  94. 'Turn on debug mode to see stack trace.'
  95. ), e
  96. )
  97. }
  98. }
  99. // "touch" every property so they are all tracked as
  100. // dependencies for deep watching
  101. if (this.deep) {
  102. traverse(value)
  103. }
  104. if (this.preProcess) {
  105. value = this.preProcess(value)
  106. }
  107. if (this.filters) {
  108. value = vm._applyFilters(value, null, this.filters, false)
  109. }
  110. this.afterGet()
  111. return value
  112. }
  113. /**
  114. * Set the corresponding value with the setter.
  115. *
  116. * @param {*} value
  117. */
  118. Watcher.prototype.set = function (value) {
  119. var vm = this.vm
  120. if (this.filters) {
  121. value = vm._applyFilters(
  122. value, this.value, this.filters, true)
  123. }
  124. try {
  125. this.setter.call(vm, vm, value)
  126. } catch (e) {
  127. if (
  128. process.env.NODE_ENV !== 'production' &&
  129. config.warnExpressionErrors
  130. ) {
  131. _.warn(
  132. 'Error when evaluating setter "' +
  133. this.expression + '"', e
  134. )
  135. }
  136. }
  137. }
  138. /**
  139. * Prepare for dependency collection.
  140. */
  141. Watcher.prototype.beforeGet = function () {
  142. Dep.target = this
  143. this.newDeps = []
  144. }
  145. /**
  146. * Clean up for dependency collection.
  147. */
  148. Watcher.prototype.afterGet = function () {
  149. Dep.target = null
  150. var i = this.deps.length
  151. while (i--) {
  152. var dep = this.deps[i]
  153. if (dep) {
  154. dep.removeSub(this)
  155. }
  156. }
  157. this.deps = this.newDeps
  158. this.newDeps = null
  159. }
  160. /**
  161. * Subscriber interface.
  162. * Will be called when a dependency changes.
  163. *
  164. * @param {Boolean} shallow
  165. */
  166. Watcher.prototype.update = function (shallow) {
  167. if (this.lazy) {
  168. this.dirty = true
  169. } else if (this.sync || !config.async) {
  170. this.run()
  171. } else {
  172. // if queued, only overwrite shallow with non-shallow,
  173. // but not the other way around.
  174. this.shallow = this.queued
  175. ? shallow
  176. ? this.shallow
  177. : false
  178. : !!shallow
  179. this.queued = true
  180. // record before-push error stack in debug mode
  181. /* istanbul ignore if */
  182. if (process.env.NODE_ENV !== 'production' && config.debug) {
  183. this.prevError = new Error('[vue] async stack trace')
  184. }
  185. batcher.push(this)
  186. }
  187. }
  188. /**
  189. * Batcher job interface.
  190. * Will be called by the batcher.
  191. */
  192. Watcher.prototype.run = function () {
  193. if (this.active) {
  194. var value = this.get()
  195. if (
  196. value !== this.value ||
  197. // Deep watchers and Array watchers should fire even
  198. // when the value is the same, because the value may
  199. // have mutated; but only do so if this is a
  200. // non-shallow update (caused by a vm digest).
  201. ((_.isArray(value) || this.deep) && !this.shallow)
  202. ) {
  203. // set new value
  204. var oldValue = this.value
  205. this.value = value
  206. // in debug + async mode, when a watcher callbacks
  207. // throws, we also throw the saved before-push error
  208. // so the full cross-tick stack trace is available.
  209. var prevError = this.prevError
  210. /* istanbul ignore if */
  211. if (process.env.NODE_ENV !== 'production' &&
  212. config.debug && prevError) {
  213. this.prevError = null
  214. try {
  215. this.cb.call(this.vm, value, oldValue)
  216. } catch (e) {
  217. _.nextTick(function () {
  218. throw prevError
  219. }, 0)
  220. throw e
  221. }
  222. } else {
  223. this.cb.call(this.vm, value, oldValue)
  224. }
  225. }
  226. this.queued = this.shallow = false
  227. }
  228. }
  229. /**
  230. * Evaluate the value of the watcher.
  231. * This only gets called for lazy watchers.
  232. */
  233. Watcher.prototype.evaluate = function () {
  234. // avoid overwriting another watcher that is being
  235. // collected.
  236. var current = Dep.target
  237. this.value = this.get()
  238. this.dirty = false
  239. Dep.target = current
  240. }
  241. /**
  242. * Depend on all deps collected by this watcher.
  243. */
  244. Watcher.prototype.depend = function () {
  245. var i = this.deps.length
  246. while (i--) {
  247. this.deps[i].depend()
  248. }
  249. }
  250. /**
  251. * Remove self from all dependencies' subcriber list.
  252. */
  253. Watcher.prototype.teardown = function () {
  254. if (this.active) {
  255. // remove self from vm's watcher list
  256. // we can skip this if the vm if being destroyed
  257. // which can improve teardown performance.
  258. if (!this.vm._isBeingDestroyed) {
  259. this.vm._watchers.$remove(this)
  260. }
  261. var i = this.deps.length
  262. while (i--) {
  263. this.deps[i].removeSub(this)
  264. }
  265. this.active = false
  266. this.vm = this.cb = this.value = null
  267. }
  268. }
  269. /**
  270. * Recrusively traverse an object to evoke all converted
  271. * getters, so that every nested property inside the object
  272. * is collected as a "deep" dependency.
  273. *
  274. * @param {Object} obj
  275. */
  276. function traverse (obj) {
  277. var key, val, i
  278. for (key in obj) {
  279. val = obj[key]
  280. if (_.isArray(val)) {
  281. i = val.length
  282. while (i--) traverse(val[i])
  283. } else if (_.isObject(val)) {
  284. traverse(val)
  285. }
  286. }
  287. }
  288. module.exports = Watcher