2017-11-07 6 views
0

コードES6の方が良ければ、重複を避けるために構造を使用するのが良いでしょうか?どのように私はparamsと各機能のためのオプションを破壊するのですか?

他の機能で同じparamsoptionsをどのように使用しますか?Class?以下のような

例:

const params = [ 
    title, 
    text, 
    confirm, 
    buttonConfirm || "Ok", 
    buttonCancel || "Cancel", 
]; 
const options = { 
    title: params.title, 
    text: params.text, 
    confirmButtonText: params.buttonConfirm, 
    cancelButtonText: params.buttonCancel, 
    showCancelButton: Boolean(params.confirm), 
}; 

class Alert { 
    success(...params) { 
    alertPlugin({ 
     ...options, 
     type: "success", 
    }).then(
    () => params.confirm() 
    ); 
    }, 

    error(...params) { 
    alertPlugin({ 
     ...options, 
     type: "error", 
    }).then(
    () => params.confirm() 
    ); 
    }, 

    warning(...params) { 
    alertPlugin({ 
     ...options, 
     type: "warning", 
    }).then(
    () => params.confirm() 
    ); 
    } 
} 

export default Alert; 

そして、私はこのコードでメソッドを呼び出します。

this.$alert.success({ 
    "Title custom", 
    "Description custom", 
    this.callbackSuccess, 
    "Yeah!", 
    "Noo!", 
}); 
+1

どのようにこれらのメソッドを呼び出す予定ですか? – ktilcu

+0

オブジェクトのプロパティを配列に広げるためにスプレッド演算子を使うことはできません。別のオブジェクト、つまり '{... this.options}'になければなりません。オブジェクトの値を配列形式で取得する場合は、[Object.values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)を参照してください。 –

+0

@ktilcu質問を編集 –

答えて

0

私はあなたが深刻どのような破壊作品を誤解していると思います。それはテンプレートのようではない、ではない重複を避けるために役立ちます。オブジェクトプロパティから初期化される変数を作成するためのより良い構文を提供するだけです。

Rest/spread syntaxは、複数の引数を持つ関数を呼び出すのに役立ちますが、すべてはローカルスコープで配列を作成/取得します。重複を避けるために役立つわけではありません。 (Btw、オブジェクトリテラルの普及構文はES6では無効ですが、将来は機能するよう提案されています)。

コードを繰り返さないようにするには、関数を使用してください(いつものように!)。あなたのケースでは、それは

function getOptions(type, [title, text, confirm, buttonConfirm = "Ok", buttonCancel = "Cancel"]) { 
    return { 
    title, 
    text, 
    confirmButtonText: buttonConfirm, 
    cancelButtonText: buttonCancel, 
    showCancelButton: Boolean(confirm), 
    type 
    }; 
} 

export function success(...args) { 
    return alertPlugin(getOptions("success", args)); 
} 
export function error(...args) { 
    return alertPlugin(getOptions("error", args)); 
} 
export function warning(...args) { 
    return alertPlugin(getOptions("warning", args)); 
} 

ことができなかった(必要Actionsクラスを作るために - 彼らはすべてのインスタンスを必要とし、that's what one doesn't do eitherしていないとして、これらの方法は、静的してきたはずです)。

関連する問題