Skip to content

fix(reactivity): avoid wrapping extended array methods #11572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading