$watch是avalon重要又实用的属性,此方法是用于监听vm中的对象的属性变化。
监听函数有三个参数, 第一个是新值, 第二个是旧值, 第三个是发生变动的属性的名字。
$watch方法供与其他操作DOM的库一起使用的,如富文本编辑器什么. 在$watch回调里更新VM自身的属性是非常危险的事,很容易引发死循环
能监听:
第一层属性值变化;
数组长度变化;
对象属性内容变化;
不能监听:
数组内容变化;
对象长度变化
推荐使用数据格式:
[{a:123},{b:'你好'}]
支持通配符*
下面是$watch方法的的七种用法:
var vm = avalon.define({
$id: "test",
array: [1, 2, 3],
d: 888,
arr: [{
a: 1
}, {
a: 2
}, {
a: 3
}],
obj: {
a: 1,
b: 2
},
a: {
b: {
c: {
d: 33
}
}
}
})
var expect = function (a) {
return {
to: {
be: function (b) {
console.log(a == b)
}
}
}
}
vm.$watch("array.length", function (a, b, name) {
console.log('第一组 数组长度', name)
})
vm.$watch("arr.*.a", function (a, b, name) {
expect(a).to.be(99)
expect(b).to.be(1)
console.log('第二组 数组元素属性(模糊匹配, 不知道哪个元素变化)', name)
})
vm.$watch("obj.a", function (a, b, name) {
expect(a).to.be(111)
expect(b).to.be(1)
console.log('第三组 属性的属性', name)
})
vm.$watch("obj.*", function (a, b, name) {
expect(a).to.be(111)
expect(b).to.be(1)
console.log('第四组 属性的属性(模糊匹配)', name)
})
vm.$watch("a.b.c.d", function (a, b, name) {
expect(a).to.be(88)
expect(b).to.be(33)
console.log('第五组 属性的属性的属性', name)
})
vm.$watch("a.*.c.d", function (a, b, name) {
expect(a).to.be(88)
expect(b).to.be(33)
console.log('第六组 属性的属性的属性(模糊匹配)', name)
})
vm.$watch("*", function (a, b, name) {
expect(a).to.be(999)
expect(b).to.be(888)
console.log('第七组 第一层对象的任意属性(模糊匹配)', name)
})
setTimeout(function () {
vm.array.set(1, 6)
vm.array.push(99)
vm.arr[0].a = 99
vm.obj.a = 111
vm.a.b.c.d = 88
vm.d = 999
}, 100)
解除监听
$watch方法就是返回了一个函数
var unwatch = vm.$watch("array.*", function (a, b) {
expect(a).to.be(6)
expect(b).to.be(2)
})
unwatch() //移除当前$watch回调