2016-10-04 55 views
2

我已經看過ES.next裝飾器的一些例子,並注意到它可能使一個裝飾器作爲一個因子函數應用參數,或直接在最後同時省略()直接或作爲工廠函數調用ES.next裝飾器

我設法讓兩種款式分開使用,作爲工廠功能@decorate(withArgs),或直接使用@decorate,但不能同時使用!

下面是一個例子: https://github.com/jayphelps/core-decorators.js#deprecate-alias-deprecated

class foo { 

    @deprecate 
    foo() {} 

    @deprecate("with an optional string") 
    bar() {} 
} 

我試圖考察上面提到的源代碼,但我與裝飾有限的經驗,我無法弄清楚如何建立類似的東西。


下面是如何設法@decorate不使用任何參數

function decorate(target, key, descriptor) { 
    // do some stuff and then return the new descriptor 
} 

工作,這裏就是我如何設法@decorate(args)帶參數的工廠函數工作:

function decorate(...args) { 
    return function(target, key, descriptor) { 
    // do some stuff using args and then return the new descriptor 
    } 
} 

正如你所看到的那樣,它可能是decorate foo()decorate(args) foo(),而不是兩者。

+0

您是否編寫了自己的@deprecate實現(如果是這樣,發佈它)?或者你難以讓他們的例子工作? –

+0

@RobM。我更新了這個問題以顯示我的實現,我並不關心'deprecate'的實際實現。我試圖讓裝飾者在最後使用或不使用'()'。 – Wazeem

+0

嗨,如果我的答案解決了您的問題,您能否將其標記爲已接受? – Dogoku

回答

3

當寫@decorator瀏覽器預計裝飾函數被調用立即,那裏的,寫@decorator(args)當它預期工廠首次被調用,它會返回一個裝飾功能

下面是增加了一個狀態屬性由終極版

export default function state (defaultState) { 

    function reducer(state, action) { 
     if (!state) { 
      state = defaultState; 
     } 
     ... 
    } 

    function decorator (target) {...} 

    // If 1st argument is a function, it means `@state` was written 
    if (typeof defaultState === 'function') { 
     let target = defaultState; 
     defaultState = {}; 
     return decorator(target); 
    } else { 
     return decorator; 
    } 
} 

驅動待辦事項類 一個裝飾我寫的一個例子,在該例子中,裝飾是類裝飾 ,這 具有不同的簽名(target)方法裝飾你 寫作(target, key, descriptor)

裝飾器可以帶有或不帶有參數

import state from './decorators/redux-state' 

@state({ 
    name: '', 
}) 
class MyClass { 
    ... 
} 

@state 
class MyOtherClass { 
    constructor(state= {name: ''}) { 
     this.state = state; 
    } 
    ... 
} 

周杰倫菲爾普斯被使用,則提取搞清楚裝飾如何被調用的decorate效用函數的邏輯,而的Makis他的代碼難於跟隨。

希望這會有所幫助