UNPKG

954 BJavaScriptView Raw
1/*
2 * not type checking this file because flow doesn't play well with
3 * dynamically accessing methods on Array prototype
4 */
5
6import { def } from '../util/index'
7
8const arrayProto = Array.prototype
9export const arrayMethods = Object.create(arrayProto)
10
11const methodsToPatch = [
12 'push',
13 'pop',
14 'shift',
15 'unshift',
16 'splice',
17 'sort',
18 'reverse'
19]
20
21/**
22 * Intercept mutating methods and emit events
23 */
24methodsToPatch.forEach(function (method) {
25 // cache original method
26 const original = arrayProto[method]
27 def(arrayMethods, method, function mutator (...args) {
28 const result = original.apply(this, args)
29 const ob = this.__ob__
30 let inserted
31 switch (method) {
32 case 'push':
33 case 'unshift':
34 inserted = args
35 break
36 case 'splice':
37 inserted = args.slice(2)
38 break
39 }
40 if (inserted) ob.observeArray(inserted)
41 // notify change
42 ob.dep.notify()
43 return result
44 })
45})