From b76bdfd4375b90bd99e04ac66f65c10f94f94b4d Mon Sep 17 00:00:00 2001 From: Evan You Date: Mon, 11 Apr 2016 18:53:04 -0400 Subject: [PATCH] include watcher Set enhancement --- src/observer/watcher.js | 23 +++++++++++++---------- src/util/env.js | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/observer/watcher.js b/src/observer/watcher.js index e660cc19..01cb6cf2 100644 --- a/src/observer/watcher.js +++ b/src/observer/watcher.js @@ -6,7 +6,8 @@ import { warn, isArray, isObject, - nextTick + nextTick, + _Set as Set } from '../util/index' let uid = 0 @@ -46,8 +47,8 @@ export default function Watcher (vm, expOrFn, cb, options) { this.dirty = this.lazy // for lazy watchers this.deps = [] this.newDeps = [] - this.depIds = Object.create(null) - this.newDepIds = null + this.depIds = new Set() + this.newDepIds = new Set() this.prevError = null // for async error stacks // parse expression for getter/setter if (isFn) { @@ -138,8 +139,6 @@ Watcher.prototype.set = function (value) { Watcher.prototype.beforeGet = function () { Dep.target = this - this.newDepIds = Object.create(null) - this.newDeps.length = 0 } /** @@ -150,10 +149,10 @@ Watcher.prototype.beforeGet = function () { Watcher.prototype.addDep = function (dep) { var id = dep.id - if (!this.newDepIds[id]) { - this.newDepIds[id] = true + if (!this.newDepIds.has(id)) { + this.newDepIds.add(id) this.newDeps.push(dep) - if (!this.depIds[id]) { + if (!this.depIds.has(id)) { dep.addSub(this) } } @@ -168,14 +167,18 @@ Watcher.prototype.afterGet = function () { var i = this.deps.length while (i--) { var dep = this.deps[i] - if (!this.newDepIds[dep.id]) { + if (!this.newDepIds.has(dep.id)) { dep.removeSub(this) } } + var tmp = this.depIds this.depIds = this.newDepIds - var tmp = this.deps + this.newDepIds = tmp + this.newDepIds.clear() + tmp = this.deps this.deps = this.newDeps this.newDeps = tmp + this.newDeps.length = 0 } /** diff --git a/src/util/env.js b/src/util/env.js index aca899d3..7a7a80ca 100644 --- a/src/util/env.js +++ b/src/util/env.js @@ -104,3 +104,26 @@ export const nextTick = (function () { timerFunc(nextTickHandler, 0) } })() + +let _Set +/* istanbul ignore if */ +if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) { + // use native Set when available. + _Set = Set +} else { + // a non-standard Set polyfill that only works with primitive keys. + _Set = function () { + this.set = Object.create(null) + } + _Set.prototype.has = function (key) { + return this.set[key] !== undefined + } + _Set.prototype.add = function (key) { + this.set[key] = 1 + } + _Set.prototype.clear = function () { + this.set = Object.create(null) + } +} + +export { _Set }