2017-10-15 39 views
0

我不明白爲什麼結果是「組件之前的指令」。裝飾者的運行順序是什麼?

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(); 

輸出:

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

不應該component calldirective call過嗎?

+2

爲什麼你覺得呢?裝飾者適用於他們下面的東西,所以適用「內外」。 – jonrsharpe

+0

我從某處讀取它,裝飾器從左到右,從上到下運行 – Hao

+0

這在手冊中直接介紹https://www.typescriptlang.org/docs/handbook/decorators.html#decorator-composition –

回答

0

的裝飾表達得到所謂自上而下,併產生裝飾。
的裝飾自己運行相反的方向,從下到上:

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

在您的例子

{ 
    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

0

組件調用在指令調用之前不應該進行嗎?

號碼內部會在外部之前被呼叫。從本質上講

@C 
@D 
class Person {} 

變爲東西類似於:

C(D(class Person()))