[0]laya下优雅的节流/去抖装饰器

讲装饰器的文章一抓一大把,这里就不详细描述了。装饰器只可以修饰类和类属性。1.安装tslib
tslib是一个的运行时库,其中包含所有TypeScript辅助函数。 该库需要在tsconfig中的开启--importHelpers标志使用.
项目目录下: npm i tslib2.配置tsconfig
[code]"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noEmitHelpers": true,
"sourceMap": true,
"importHelpers": true,
"experimentalDecorators": true,
"baseUrl": ".", //必需,否则paths配置不会生效
"paths": {
"tslib": [
"tslib/tslib.d.ts"
]
}
}

[/code]3.装饰器例子
装饰类属性的时候,就需要在装饰函数中使用三个参数:
target
name
descriptor
,分别代表了需要修饰的目标类、目标属性、目标属性的描述符。
写装饰器的时候一定要弄清楚
this
指向的几种规则:
  1. 当一个函数使用
    new
    操作符来调用的时候,在函数内部
    this
    指向了新创建的对象。
  2. 当使用
    call
    apply
    调用函数的时候,
    this
    指向了
    call
    apply
    指定的第一个参数。如果第一个参数是
    null
    或者不是一个对象的时候,
    this
    指向全局对象。
  3. 当函数作为对象里面的属性被调用的时候,在函数内部的
    this
    指向了对应的对象。
  4. 最后就是默认规则,默认
    this
    指向全局对象,在浏览器便是Window。但是在严格模式下是为
    undefined
    的。

[code]/**
* 函数节流装饰器
* @param wait: 节流时间
*/
export function throttle(wait: number) {
let previous = 0;
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const oldValue = descriptor.value
descriptor.value = function (...args) {
const now = Date.now();
if (now - previous > wait) {
oldValue.apply(this, args)
previous = now;
}
};
return descriptor
}
}
[/code]
[code]/**
* 函数去抖动装饰器(立即执行版)
* @param wait: 去抖时间
*/
export function debounce(wait: number) {
let timeout;
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const oldValue = descriptor.value
descriptor.value = function (...args) {
if (timeout) clearTimeout(timeout);
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) oldValue.apply(this, args)
};
return descriptor
}
}
[/code]4.使用方法
优雅的节流器使用方法
@throttle(500)功能:限制触发该函数后500ms后才能再次触发.应用场景: 通常可以用来限制过快的点击的回调.
@debounce(500)功能:限制触发该函数后500ms内没有调用过才能再次触发(立即执行版). 应用场景: 通常可以用来限制mousemove事件,输入框输入事件等.他们触发的很频繁,这个时候函数没必要一直执行.函数防抖就是让事件触发的n秒内只执行一次,如果连续触发就重新计算时间.
[code]    @throttle(500)
private onTimeBtn() {
DialogView.show({content: i18n("确认刷新当前商店吗?"),
okFunc: Laya.Handler.create(this, () => {
this.refreshShop();
})
})
}

[attach]27756[/attach]



[/code]
已邀请:

Laya_Fred

赞同来自:

感谢您的技术分享~

要回复问题请先

商务合作
商务合作