watcher.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 scope = this.scope || vm
  82. var value
  83. try {
  84. value = this.getter.call(scope, scope)
  85. } catch (e) {
  86. if (
  87. process.env.NODE_ENV !== 'production' &&
  88. config.warnExpressionErrors
  89. ) {
  90. _.warn(
  91. 'Error when evaluating expression "' +
  92. this.expression + '". ' +
  93. (config.debug
  94. ? ''
  95. : 'Turn on debug mode to see stack trace.'
  96. ), e
  97. )
  98. }
  99. }
  100. // "touch" every property so they are all tracked as
  101. // dependencies for deep watching
  102. if (this.deep) {
  103. traverse(value)
  104. }
  105. if (this.preProcess) {
  106. value = this.preProcess(value)
  107. }
  108. if (this.filters) {
  109. value = vm._applyFilters(value, null, this.filters, false)
  110. }
  111. this.afterGet()
  112. return value
  113. }
  114. /**
  115. * Set the corresponding value with the setter.
  116. *
  117. * @param {*} value
  118. */
  119. Watcher.prototype.set = function (value) {
  120. var vm = this.vm
  121. var scope = this.scope || vm
  122. if (this.filters) {
  123. value = vm._applyFilters(
  124. value, this.value, this.filters, true)
  125. }
  126. try {
  127. this.setter.call(scope, scope, value)
  128. } catch (e) {
  129. if (
  130. process.env.NODE_ENV !== 'production' &&
  131. config.warnExpressionErrors
  132. ) {
  133. _.warn(
  134. 'Error when evaluating setter "' +
  135. this.expression + '"', e
  136. )
  137. }
  138. }
  139. }
  140. /**
  141. * Prepare for dependency collection.
  142. */
  143. Watcher.prototype.beforeGet = function () {
  144. Dep.target = this
  145. this.newDeps = []
  146. }
  147. /**
  148. * Clean up for dependency collection.
  149. */
  150. Watcher.prototype.afterGet = function () {
  151. Dep.target = null
  152. var i = this.deps.length
  153. while (i--) {
  154. var dep = this.deps[i]
  155. if (dep) {
  156. dep.removeSub(this)
  157. }
  158. }
  159. this.deps = this.newDeps
  160. this.newDeps = null
  161. }
  162. /**
  163. * Subscriber interface.
  164. * Will be called when a dependency changes.
  165. *
  166. * @param {Boolean} shallow
  167. */
  168. Watcher.prototype.update = function (shallow) {
  169. if (this.lazy) {
  170. this.dirty = true
  171. } else if (this.sync || !config.async) {
  172. this.run()
  173. } else {
  174. // if queued, only overwrite shallow with non-shallow,
  175. // but not the other way around.
  176. this.shallow = this.queued
  177. ? shallow
  178. ? this.shallow
  179. : false
  180. : !!shallow
  181. this.queued = true
  182. // record before-push error stack in debug mode
  183. /* istanbul ignore if */
  184. if (process.env.NODE_ENV !== 'production' && config.debug) {
  185. this.prevError = new Error('[vue] async stack trace')
  186. }
  187. batcher.push(this)
  188. }
  189. }
  190. /**
  191. * Batcher job interface.
  192. * Will be called by the batcher.
  193. */
  194. Watcher.prototype.run = function () {
  195. if (this.active) {
  196. var value = this.get()
  197. if (
  198. value !== this.value ||
  199. // Deep watchers and Array watchers should fire even
  200. // when the value is the same, because the value may
  201. // have mutated; but only do so if this is a
  202. // non-shallow update (caused by a vm digest).
  203. ((_.isArray(value) || this.deep) && !this.shallow)
  204. ) {
  205. // set new value
  206. var oldValue = this.value
  207. this.value = value
  208. // in debug + async mode, when a watcher callbacks
  209. // throws, we also throw the saved before-push error
  210. // so the full cross-tick stack trace is available.
  211. var prevError = this.prevError
  212. /* istanbul ignore if */
  213. if (process.env.NODE_ENV !== 'production' &&
  214. config.debug && prevError) {
  215. this.prevError = null
  216. try {
  217. this.cb.call(this.vm, value, oldValue)
  218. } catch (e) {
  219. _.nextTick(function () {
  220. throw prevError
  221. }, 0)
  222. throw e
  223. }
  224. } else {
  225. this.cb.call(this.vm, value, oldValue)
  226. }
  227. }
  228. this.queued = this.shallow = false
  229. }
  230. }
  231. /**
  232. * Evaluate the value of the watcher.
  233. * This only gets called for lazy watchers.
  234. */
  235. Watcher.prototype.evaluate = function () {
  236. // avoid overwriting another watcher that is being
  237. // collected.
  238. var current = Dep.target
  239. this.value = this.get()
  240. this.dirty = false
  241. Dep.target = current
  242. }
  243. /**
  244. * Depend on all deps collected by this watcher.
  245. */
  246. Watcher.prototype.depend = function () {
  247. var i = this.deps.length
  248. while (i--) {
  249. this.deps[i].depend()
  250. }
  251. }
  252. /**
  253. * Remove self from all dependencies' subcriber list.
  254. */
  255. Watcher.prototype.teardown = function () {
  256. if (this.active) {
  257. // remove self from vm's watcher list
  258. // we can skip this if the vm if being destroyed
  259. // which can improve teardown performance.
  260. if (!this.vm._isBeingDestroyed) {
  261. this.vm._watchers.$remove(this)
  262. }
  263. var i = this.deps.length
  264. while (i--) {
  265. this.deps[i].removeSub(this)
  266. }
  267. this.active = false
  268. this.vm = this.cb = this.value = null
  269. }
  270. }
  271. /**
  272. * Recrusively traverse an object to evoke all converted
  273. * getters, so that every nested property inside the object
  274. * is collected as a "deep" dependency.
  275. *
  276. * @param {Object} obj
  277. */
  278. function traverse (obj) {
  279. var key, val, i
  280. for (key in obj) {
  281. val = obj[key]
  282. if (_.isArray(val)) {
  283. i = val.length
  284. while (i--) traverse(val[i])
  285. } else if (_.isObject(val)) {
  286. traverse(val)
  287. }
  288. }
  289. }
  290. module.exports = Watcher