Skip to content

Commit

Permalink
fix(reactivity): avoid wrapping extended array methods (#11572)
Browse files Browse the repository at this point in the history
close #11570
  • Loading branch information
edison1105 authored Aug 9, 2024
1 parent 6acb046 commit bf33217
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
17 changes: 17 additions & 0 deletions packages/reactivity/__tests__/reactiveArray.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -622,5 +622,22 @@ describe('reactivity/reactive/Array', () => {
const firstItem = Array.from(deep.values())[0]
expect(isReactive(firstItem)).toBe(true)
})

test('extend methods', () => {
class Collection extends Array {
find(id: any) {
return super.find(obj => obj.id === id)
}
}

const state = reactive({
things: new Collection(),
})

const val = { id: 'foo', value: 'bar' }
state.things.push(val)

expect(state.things.find('foo')).toBe(val)
})
})
})
10 changes: 8 additions & 2 deletions packages/reactivity/src/arrayInstrumentations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ function iterator(
// higher than that
type ArrayMethods = keyof Array<any> | 'findLast' | 'findLastIndex'

const arrayProto = Array.prototype
// instrument functions that read (potentially) all items
// to take ARRAY_ITERATE dependency
function apply(
Expand All @@ -237,6 +238,12 @@ function apply(
wrappedRetFn?: (result: any) => unknown,
) {
const arr = shallowReadArray(self)
let methodFn
// @ts-expect-error our code is limited to es2016 but user code is not
if ((methodFn = arr[method]) !== arrayProto[method]) {
return methodFn.apply(arr, arrayProto.slice.call(arguments, 2))
}

let needsWrap = false
let wrappedFn = fn
if (arr !== self) {
Expand All @@ -251,8 +258,7 @@ function apply(
}
}
}
// @ts-expect-error our code is limited to es2016 but user code is not
const result = arr[method](wrappedFn, thisArg)
const result = methodFn.call(arr, wrappedFn, thisArg)
return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result
}

Expand Down

0 comments on commit bf33217

Please sign in to comment.