【问题标题】:How does angular method decorator work?角度方法装饰器如何工作?
【发布时间】:2017-10-20 00:08:18
【问题描述】:

在这个Angular decorator tutorial 中,教程解释了throttle 装饰器(lodash throttle 函数)可以这样制作:

import t from 'lodash.throttle';

export function throttle( milliseconds : number = 500 ) : MethodDecorator {
   return function ( target : any, propertyKey : string, descriptor : PropertyDescriptor ) {
   const original = descriptor.value;
   descriptor.value = t(original, milliseconds);
   return descriptor;
  };
}

并在下面的类中使用

@Component({
  selector: 'app-posts-page',
  template: `
     <posts [posts]="posts$ | async"></posts>
  `
})
export class PostsPageComponent {
  constructor( private store : Store<any> ) {
    this.posts$ = store.select('posts');
  }

  @HostListener('document:scroll')
  @throttle()
  scroll() {
    console.log('scroll');
  }
}

我想知道油门是如何改变滚动功能的。谁能解释或让我知道如何查看编译后的代码?谢谢!

【问题讨论】:

    标签: javascript angular angular-decorator


    【解决方案1】:

    throttle 是一个属性装饰器,这意味着它的工作通常是修改类(对象)property descriptor。修改前的描述符有value指向scroll函数:

    {
      value: scroll() { console.log('scroll'); },
      ...
    }
    

    装饰器接受这个描述符并用调用t返回的新装饰函数替换原来的value

    function ( target : any, propertyKey : string, descriptor : PropertyDescriptor ) {
       // save original value 'scroll'
       const original = descriptor.value;
       // overwrite original value with the decorated function returned by `t`
       descriptor.value = t(original, milliseconds);
       return descriptor;
    };
    

    如果装饰器返回描述符,那么它将用于定义属性而不是原始描述符。

    您可以在文章中阅读有关装饰器的更多信息:

    【讨论】:

    • 所有方法都有描述符,因为方法是指向函数的属性
    猜你喜欢
    • 2020-05-28
    • 2014-04-24
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多