Skip to content

Commit 1bbaab3

Browse files
committed
add directive deep option
1 parent dc1f4a9 commit 1bbaab3

File tree

3 files changed

+40
-6
lines changed

3 files changed

+40
-6
lines changed

src/directive.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ p._bind = function (def) {
8585
this._watcherExp,
8686
update, // callback
8787
this.filters,
88-
this.twoWay // need setter
88+
this.twoWay, // need setter,
89+
this.deep
8990
)
9091
} else {
9192
watcher.addCb(update)

src/watcher.js

+24-4
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,11 @@ p.get = function () {
7575
} catch (e) {
7676
_.warn(e)
7777
}
78-
// use JSON.stringify to "touch" every property
79-
// so they are all tracked as dependencies for
80-
// deep watching
81-
if (this.deep) JSON.stringify(value)
78+
// "touch" every property so they are all tracked as
79+
// dependencies for deep watching
80+
if (this.deep) {
81+
traverse(value)
82+
}
8283
value = _.applyFilters(value, this.readFilters, vm)
8384
this.afterGet()
8485
return value
@@ -214,4 +215,23 @@ p.teardown = function () {
214215
}
215216
}
216217

218+
219+
/**
220+
* Recrusively traverse an object to evoke all converted
221+
* getters, so that every nested property inside the object
222+
* is collected as a "deep" dependency.
223+
*
224+
* @param {Object} obj
225+
*/
226+
227+
function traverse (obj) {
228+
var key, val
229+
for (key in obj) {
230+
val = obj[key]
231+
if (_.isObject(val)) {
232+
traverse(val)
233+
}
234+
}
235+
}
236+
217237
module.exports = Watcher

test/unit/specs/directive_spec.js

+14-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ describe('Directive', function () {
1515
}
1616
vm = new Vue({
1717
data:{
18-
a:1
18+
a:1,
19+
b: { c: 2 }
1920
},
2021
filters: {
2122
test: function (v) {
@@ -148,6 +149,18 @@ describe('Directive', function () {
148149
})
149150
})
150151

152+
it('deep', function (done) {
153+
def.deep = true
154+
var d = new Directive('test', el, vm, {
155+
expression: 'b'
156+
}, def)
157+
vm.b.c = 3
158+
nextTick(function () {
159+
expect(def.update.calls.count()).toBe(2)
160+
done()
161+
})
162+
})
163+
151164
it('function def', function () {
152165
var d = new Directive('test', el, vm, {
153166
expression: 'a'

0 commit comments

Comments
 (0)