knockout

An introduction for WPFists

MVVM for Javascript

  • Dependency tracking
  • Automatic UI refresh
  • Declarative bindings

Basic Property binding

Knockout

<div>You've clicked <span data-bind='text: numberOfClicks'>&nbsp;</span> times</div>

WPF

<TextBlock>
  <TextBlock.Inlines>
    <Run>You've clicked </Run>
    <Run Text="{Binding NumberOfClicks.Value}"/>
    <Run> times</Run>
  </TextBlock.Inlines>
</TextBlock>

Command binding

Knockout
<button 
  data-bind='click: registerClick, disable: hasClickedTooManyTimes'>
  Click me
</button>

WPF
<Button Command="{Binding RegisterClickCommand}"> Click me</Button>
ICommand

public ICommand RegisterClickCommand
{
  get { return new RelayCommand(
    RegisterClick, () => !HasClickedTooManyTimes.Value); }
}

Visible binding

Knockout
<div data-bind='visible: hasClickedTooManyTimes'>
    That's too many clicks! Please stop before you wear out your fingers.
    <button data-bind='click: resetClicks'>Reset clicks</button>
</div>

WPF
<StackPanel Orientation="Horizontal">
  <StackPanel.Visibility>
    <Binding Path="HasClickedTooManyTimes.Value">
      <Binding.Converter>
        <BooleanToVisibilityConverter />
      </Binding.Converter>
    </Binding>
  </StackPanel.Visibility>
  <TextBlock>That's too many clicks! Please stop before you wear out your fingers.</TextBlock>
  <Button Command="{Binding ResetClicks}">Reset clicks</Button>
</StackPanel>

Viewmodel

Knockout
var ClickCounterViewModel = function() {
    this.numberOfClicks = ko.observable(0);
 
    this.registerClick = function() {
        this.numberOfClicks(this.numberOfClicks() + 1);
    };
 
    this.resetClicks = function() {
        this.numberOfClicks(0);
    };
 
    this.hasClickedTooManyTimes = ko.computed(function() {
        return this.numberOfClicks() >= 3;
    }, this);
};
WPF 

Apply Bindings

Knockout
ko.applyBindings(new ClickCounterViewModel());

WPF
public partial class MainWindow : Window
{
    public MainWindow()
    {
        DataContext = new MainWindowViewModel();
        InitializeComponent();
    }
}

knockout In Web Apps


WPF MVVM


CEF MVVM


Demo

Next Steps

  • Code is proof of concept - not production ready

  • Doesn't work for deeply nested types

  • Open source it!
Made with Slides.com