Skip to content

Commit

Permalink
add directive deep option
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Nov 30, 2014
1 parent dc1f4a9 commit 1bbaab3
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/directive.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ p._bind = function (def) {
this._watcherExp,
update, // callback
this.filters,
this.twoWay // need setter
this.twoWay, // need setter,
this.deep
)
} else {
watcher.addCb(update)
Expand Down
28 changes: 24 additions & 4 deletions src/watcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,11 @@ p.get = function () {
} catch (e) {
_.warn(e)
}
// use JSON.stringify to "touch" every property
// so they are all tracked as dependencies for
// deep watching
if (this.deep) JSON.stringify(value)
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
value = _.applyFilters(value, this.readFilters, vm)
this.afterGet()
return value
Expand Down Expand Up @@ -214,4 +215,23 @@ p.teardown = function () {
}
}


/**
* Recrusively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*
* @param {Object} obj
*/

function traverse (obj) {
var key, val
for (key in obj) {
val = obj[key]
if (_.isObject(val)) {
traverse(val)
}
}
}

module.exports = Watcher
15 changes: 14 additions & 1 deletion test/unit/specs/directive_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ describe('Directive', function () {
}
vm = new Vue({
data:{
a:1
a:1,
b: { c: 2 }
},
filters: {
test: function (v) {
Expand Down Expand Up @@ -148,6 +149,18 @@ describe('Directive', function () {
})
})

it('deep', function (done) {
def.deep = true
var d = new Directive('test', el, vm, {
expression: 'b'
}, def)
vm.b.c = 3
nextTick(function () {
expect(def.update.calls.count()).toBe(2)
done()
})
})

it('function def', function () {
var d = new Directive('test', el, vm, {
expression: 'a'
Expand Down

0 comments on commit 1bbaab3

Please sign in to comment.