2017-08-07 67 views
6

窗口上有幾個按鈕,我嘗試找到處理命令的好方法。使用Gjallarhorn處理多個命令(從按鈕)的正確方法

例如:

我必須執行某些操作:

type Action = 
    |Show 
    |Open 
    |Input 
    |Change 
    |Statistic 

翻譯這個到XAML將是:

<Button Command="{Binding ShowCommand}" /> 
<Button Command="{Binding OpenCommand}" /> 
<Button Command="{Binding InputCommand}" /> 
<Button Command="{Binding ChangeCommand}" /> 
<Button Command="{Binding StatisticCommand}" /> 

位與庫打我發現兩種方法不用煩人詳細地做它

1. 使用Observable.merge

Binding.createMessage "StatisticCommand" Statistic source 
|> Observable.merge (Binding.createMessage "InputCommand" Input source) 
//|> Observable.merge ... and so on 
|> Observable.subscribe (performAction model.Value) 
|> source.AddDisposable 

2. 創建推廣消息

type GeneralMessage = 
    |Perform of Action 
    |Update of Message 

,提高了動作消息高電平

let mainComponent source (model : ISignal<Info>) = 

    let info = Binding.componentToView source "Info" infoComponent model 
    //... 

    let stat = Binding.createMessage "StatCommand" (Perform Statistic) source 
    let input = Binding.createMessage "InputCommand" (Perform Input) source 
    //let ... 

    [info; stat; input; ...] 

let appComponent = 
    let model = initInfo 
    let update message model = 
     match message with 
     |Update message -> 
      match message with 
      |... 
     |Perform action -> 
      performAction model action 
      model 

    Framework.basicApplication model update mainComponent 

(好吧,我想第一個選項,導致此操作不改變型號)

是否正確的方法(第一,明顯)做這些事情或庫包含更多的擬合功能?

P.S.我尋找Observable.concat [info; stat; input; ...],但沒有幸運。

回答

5

所以任何選項都很好。我認爲合適的方法取決於如何使用此方法,以及需要什麼數據:

  • 如果「操作」是應該由組件被全部處理,第一個選項是完全有效的。這將該組件的工作封裝在該函數中以設置綁定,並將其完全保留在模型之外。

  • 如果「動作」需要模型外的任何東西(或模型的可用部分),則向上傳播(如選項2)最有意義。這允許模型與該操作一起工作,並且適當地處理它。