vant-weapp/packages/mixins/page-scroll.ts
2020-05-07 14:50:21 +08:00

46 lines
1.2 KiB
TypeScript

type IPageScrollOption = WechatMiniprogram.Page.IPageScrollOption;
type Scroller = (event: IPageScrollOption) => void;
type TrivialInstance = WechatMiniprogram.Page.TrivialInstance & {
vanPageScroller?: Scroller[];
};
function getCurrentPage(): TrivialInstance {
const pages = getCurrentPages();
return pages[pages.length - 1] || ({} as TrivialInstance);
}
function onPageScroll(event: IPageScrollOption) {
const { vanPageScroller = [] } = getCurrentPage();
vanPageScroller.forEach((scroller: Scroller) => {
if (typeof scroller === 'function') {
scroller(event);
}
});
}
export const pageScrollMixin = (scroller: Scroller) =>
Behavior({
attached() {
const page = getCurrentPage();
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)];
}
page.onPageScroll = onPageScroll;
},
detached() {
const page = getCurrentPage();
page.vanPageScroller = (page.vanPageScroller || []).filter(
(item) => item !== scroller
);
},
});