Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the decorator running order?

I don't understand why the result is "directive before component".

function Component(component) {
    console.log('selector: ' + component.selector);
    console.log('template: ' + component.template);
    console.log('component init');
    return (target: any) => {
        console.log('component call');
        return target;
    }
}

function Directive() {
    console.log('directive init');
    return (target: any) => {
        console.log('directive call');
        return target;
    }

}

@Component({selector: 'person',template: 'person.html'})
@Directive()
class Person {}

let p = new Person();

Output:

selector: person
template: person.html
component init
directive init
directive call
component call

Shouldn't the component call be before directive call?

like image 612
Hao Avatar asked Oct 15 '17 17:10

Hao


1 Answers

The decorator expressions get called top to bottom, and produce decorators.
The decorators themselves run in the opposite direction, bottom to top:

@a @b x
// bit like
{
  const decA = a
  const decB = b
  decA(decB(x))
}

In your example

{
  const decComp = Component({selector: 'person', template: 'person.html'})
  // selector: person
  // template: person.html
  // component init
  const decDirective = Directive()
  // directive init
  decComp(decDirective(Person))
  // directive call
  // component call
}

Reference

like image 172
HTNW Avatar answered Dec 04 '22 06:12

HTNW