blob: 856792fea833830aef5c6baf6063d3639b053a46 [file] [log] [blame]
/* eslint-disable */
import { def } from '../util/index'
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
/**
* Intercept mutating methods and emit events
*/
;[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator () {
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
let i = arguments.length
const args = new Array(i)
while (i--) {
args[i] = arguments[i]
}
const result = original.apply(this, args)
const ob = this.__ob__
let inserted
switch (method) {
case 'push':
inserted = args
break
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
/**
* Swap the element at the given index with a new value
* and emits corresponding event.
*
* @param {Number} index
* @param {*} val
* @return {*} - replaced element
*/
def(
arrayProto,
'$set',
function $set (index, val) {
console.warn(`[JS Framework] "Array.prototype.$set" is not a standard API,`
+ ` it will be removed in the next version.`)
if (index >= this.length) {
this.length = index + 1
}
return this.splice(index, 1, val)[0]
}
)
/**
* Convenience method to remove the element at given index.
*
* @param {Number} index
* @param {*} val
*/
def(
arrayProto,
'$remove',
function $remove (index) {
console.warn(`[JS Framework] "Array.prototype.$remove" is not a standard API,`
+ ` it will be removed in the next version.`)
/* istanbul ignore if */
if (!this.length) return
/* istanbul ignore else */
if (typeof index !== 'number') {
index = this.indexOf(index)
}
/* istanbul ignore else */
if (index > -1) {
this.splice(index, 1)
}
}
)