Skip to content

Commit

Permalink
* [jsfm] fix calling functional data-binding multiply
Browse files Browse the repository at this point in the history
  • Loading branch information
terrykingcha committed Apr 15, 2016
1 parent cb3e465 commit dcd9b66
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
21 changes: 16 additions & 5 deletions src/js-framework/lib/vm/__test__/directive.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,18 @@ function initElement(el) {
describe('watch key or props', () => {
var vm, cb
var update = function () {return this.a + this.b}
var update2 = function () {return this.plus()}
var callPlus = sinon.spy()
var methodNames = ['_watch', '_bindKey', '_bindDir']
beforeEach(() => {
vm = {
_data: {a: 1, b: 2},
_methods: {},
_methods: {
plus: function () {
callPlus()
return this.a + this.b
}
},
_watchers: [],
_app: {}
}
Expand All @@ -68,6 +75,7 @@ describe('watch key or props', () => {
expect(cb).calledTwice
expect(cb).calledWith(5)
})

// - update object key-value when data source changed
it('watch k-v pairs', () => {
var el = {attr: {c: 3}}
Expand All @@ -87,14 +95,17 @@ describe('watch key or props', () => {
it('watch element props', () => {
var el = {attr: {c: 3}}
initElement(el)
vm._bindDir(el, 'attr', {d: 4, e: update})
expect(el.attr).eql({c: 3, d: 4, e: 3})
vm._bindDir(el, 'attr', {d: 4, e: update, f: update2})
expect(el.attr).eql({c: 3, d: 4, e: 3, f: 3})
expect(callPlus).calledOnce
vm.a = 2
expect(vm._data).eql({a: 2, b: 2})
expect(el.attr).eql({c: 3, d: 4, e: 4})
expect(el.attr).eql({c: 3, d: 4, e: 4, f: 4})
expect(callPlus).calledTwice
vm.b = 3
expect(vm._data).eql({a: 2, b: 3})
expect(el.attr).eql({c: 3, d: 4, e: 5})
expect(el.attr).eql({c: 3, d: 4, e: 5, f: 5})
expect(callPlus).calledThird
})
})

Expand Down
11 changes: 7 additions & 4 deletions src/js-framework/lib/vm/directive.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,8 @@ export function _bindDir(el, name, data) {
export function _bindKey(el, name, key, calc) {
const methodName = SETTERS[name]
const obj = el[name]
const value = calc.call(this)
el[methodName](key, calc.call(this))
this._watch(calc, (value) => {
// watch the calc, and returns a value by calc.call()
const value = this._watch(calc, (value) => {
function handler() {
el[methodName](key, value)
}
Expand All @@ -269,17 +268,21 @@ export function _bindKey(el, name, key, calc) {
handler()
}
})

el[methodName](key, value)
}

/**
* watch a calc function and callback if the calc value changes
*/
export function _watch(calc, callback) {
new Watcher(this, calc, function (value, oldValue) {
const watcher = new Watcher(this, calc, function (value, oldValue) {
/* istanbul ignore if */
if (typeof value !== 'object' && value === oldValue) {
return
}
callback(value)
})

return watcher.value
}

0 comments on commit dcd9b66

Please sign in to comment.