/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
import { def } from '../util/index'
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator (...args) {
const result = original.apply(this, args)
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
vue源码中对原生数组方法重写,请问下为什么const result = original.apply(this, args)这段代码就可以达到监听数组变化的效果?求指教,谢谢!!!
const result = original.apply(this, args)
这行不是监听,这个的作用是调用原来的原型上的数组方法,因为def
重写了数组原型方法,那么你需要还原原来的行为,比如push
操作就应该把数据推入进数组里,apply
就是借用上面取出的原方法应用,因为你不能调用现在的push
,会死循环