Intro to Knockout JS

capital laravel meetup

What is Knockout?

capital laravel meetup

Knockout is a JavaScript framework that enables two-way data binding between UI elements and data.

{
    firstName: "Daniel",
    lastName: "Abernathy
}

capital laravel meetup

Model - View - ViewModel

{
    "firstName" : "Daniel",
    "lastName" : "Abernathy",
    "age" : 25
}

capital laravel meetup

Model - View - ViewModel

<input type="text" class="first-name" data-bind="value: firstName" />

<input type="text" class="last-name" data-bind="value: lastName" />

<span class="full-name" data-bind="value: fullName"></span>

"Declarative Binding" with data attributes

capital laravel meetup

Model - View - ViewModel

function AppViewModel() {
    this.firstName = "Daniel";

    this.lastName = "Abernathy";
 
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
}

Other Knockout Concepts

capital laravel meetup

  • Observables & Observable Arrays
  • Computed Observables
  • Custom Bindings
  • Components (new)

capital laravel meetup

How does it compare?

  • Angular
  • Ember
  • Backbone

capital laravel meetup

Similarities

  • Libraries, not frameworks
  • Not very opinionated about architecture
  • Allow you to use 3rd party templating tools
  • Observable Arrays (Knockout) / Collections (backbone)

Differences

  • Backbone doesn't support two-way data binding out of the box
  • Backbone supports routing
  • M-V-VM (Knockout) vs M-V-whatever (Backbone)

Backbone

When / why should you use Knockout?

capital laravel meetup

  • Can be easily inserted into an existing project or architecture
  • If you don't want or need a single page app (or if you do!)
  • If your UI and data are tightly integrated
Made with Slides.com