watcher.js 7.1 KB

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