2017-12-08 11 views
0

私は小さなJavaScriptライブラリを作成しようとしているRubyプログラマーです。coffeeスクリプトクラスとサブクラスの変数を上書きする

私はJavaScriptの専門家ではないので、私はコーヒースクリプトを手伝っています。

アイデア:

私は機能の一部小片を共有するすべてのそれらのいくつかの小さなJavaScriptのウィジェットを作成します。

共有機能と設定はBaseクラスにあります。すべてのウィジェットはBaseから継承する独自のクラスを持ち、独自の設定(さらにはBaseの上書き設定)を設定できます。

最後に、ウィジェットがインスタンス化されると、ウィジェット自体のデフォルトオプションを上書きするオプションハッシュを渡すことができます。

それは、これまでに次のようになります。

@Adg = {} 

class Adg.Base 
    config = 
    debugMessage: false 
    hiddenCssClass: 'visually-hidden' 

    # Constructor. Should not be overridden; use @init() instead. 
    # 
    # - Arg1: The DOM element on which the script should be applied (will be saved as @$el) 
    # - Arg2: An optional hash of options which will be merged into the global default config 
    constructor: (el, options = {}) -> 
    @config = config 

    @$el = $(el) 

    for key, val of options 
     @config[key] = val 

    @init() 

    # Dummy, must be overridden in inheriting classes. 
    init: -> 
    throw 'Classes extending App must implement method init()!' 

class Adg.Autocomplete extends Adg.Base 
    config = 
    suggestionsContainer: 'fieldset' 
    suggestionsContainerLabel: 'legend' 
    alertsContainerId: 'alerts' 

    init: -> 
    # Merge config into existing one 
    for key, val of config 
     @config[key] = val 

これは私に動作しますが、不器用な感じ:

  • 私は上書きされてはならないデフォルトconstructorを作成するために持っていることを好きではありませんクラスを継承することによって(私は代わりにinit()メソッドを追加します)
  • 各継承クラスで、私は手動で構成をマージする必要があります

答えて

1

私は次のようにあなたが探しているものでしょうと信じて:

  1. をクラスのプロパティではなく、ローカル変数/クロージャを使用:

    @Adg = {} 
    
    class Adg.Base 
    
        @config = 
        debugMessage: false 
        hiddenCssClass: 'visually-hidden' 
    
        constructor: (el, options = {}) -> 
        @config = Object.assign {}, Adg.Base.config, options 
        @$el = $(el) 
    
    class Adg.Autocomplete extends Adg.Base 
    
        @config = 
        suggestionsContainer: 'fieldset' 
        suggestionsContainerLabel: 'legend' 
        alertsContainerId: 'alerts' 
    
        constructor: (el, options={}) -> 
        super(el, Object.assign({}, options, Adg.Autocomplete.config)) 
    

    私が作ったカップルの変更があります。 @configAdg.Baseは、Adg.Base.configを使用して読み取られます。

  2. superを使用して、子コンテナから親コンストラクタを呼び出します。
  3. Object.assignを使用してハッシュをマージします。

    @config = {Adg.Base.config..., config...}` 
    
    :あなたはCoffeeScriptの2(アンインストールのCoffeeScriptをし、次のパッケージ@のCoffeeScriptをインストール)を使用している場合は、あなたの代わりにObject.assignの広がり演算子を使用することができることを

注意

関連する問題