fix(mixin): fix scroll function are not recycled (#5086)

* fix(mixins): fix scroll function are not recycled

* fix(mixins): opt page scroll mixin recycle
This commit is contained in:
landluck 2022-11-03 14:42:11 +08:00 committed by GitHub
parent 66c967b782
commit 46b8d053e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,3 +1,4 @@
import { isFunction } from '../common/validator';
import { getCurrentPage, isDef } from '../common/utils';
type IPageScrollOption = WechatMiniprogram.Page.IPageScrollOption;
@ -19,32 +20,48 @@ function onPageScroll(event?: IPageScrollOption) {
});
}
export const pageScrollMixin = (scroller: Scroller) =>
Behavior({
attached() {
export function pageScrollMixin(scroller: Scroller) {
return Behavior({
attached(this: WechatMiniprogram.Component.TrivialInstance) {
const page = getCurrentPage<{ vanPageScroller: Scroller[] }>();
if (!isDef(page)) {
return;
}
if (Array.isArray(page.vanPageScroller)) {
page.vanPageScroller.push(scroller.bind(this));
} else {
page.vanPageScroller =
typeof page.onPageScroll === 'function'
? [page.onPageScroll.bind(page), scroller.bind(this)]
: [scroller.bind(this)];
const _scroller = scroller.bind(this);
const { vanPageScroller = [] } = page;
if (!vanPageScroller.length && isFunction(page.onPageScroll)) {
vanPageScroller.push(page.onPageScroll.bind(page));
}
vanPageScroller.push(_scroller);
page.vanPageScroller = vanPageScroller;
page.onPageScroll = onPageScroll;
this._scroller = _scroller;
},
detached() {
detached(this: WechatMiniprogram.Component.TrivialInstance) {
const page = getCurrentPage<{ vanPageScroller: Scroller[] }>();
if (isDef(page)) {
page.vanPageScroller =
page.vanPageScroller?.filter((item) => item !== scroller) || [];
if (!isDef(page) || !isDef(page.vanPageScroller)) {
return;
}
const { vanPageScroller } = page;
const index = vanPageScroller.findIndex(v => v === this._scroller);
if (index > -1) {
page.vanPageScroller.splice(index, 1);
}
this._scroller = undefined;
},
});
}