SlideShare a Scribd company logo
Bringing the light to the client
   with KnockoutJS

var speaker = {
   name: “Boyan Mihaylov”,
   company: “Ebita.dk”
};
About me

 Software Developer @ Ebita.dk
   Software architectures / system integration
   Best practices
   Web trends
 (Almost) Ms.c. in Computer Science @ The
  University of Copenhagen
 Teaching assistant @ UCPH
   Principles of Computer System Design
What‟s there for today?

   Why JavaScript
   Why MV* patterns
   What is KnockoutJS
   How it works
   Extensibility
Why is JavaScript so popular?

 Runs in the browser
   No 3rd-party software
 Considerably fast (in the latest browsers)
 Low entry barriers
   a.k.a. (reasonably) low learning curve
 Still in the game with HTML5
Why people hate JavaScript?

 “Few” programming misunderstandings
   Global variables
   The proper “this” in functions
   …
 Browser (in)compatibility
  Especially the blue guy
  behind
jQuery for the win!

 Rich API for DOM manipulation
   Traversing
   Event handling
   Animations
 Browser compatibility
Before & after jQuery

if (document.getElementById) ...
else if (document.layers) …        Before
else if (document.all) …



$(‟#my_id‟)                         After
But...




 Too much of a good thing is not a good thing
The rise of MV* patterns

 MV* stands for Model-View-(many variations)
   MVC (Model-View-Controller)
   MVVM (Model-View-ViewModel)
 Separation between the data and how it is
  displayed
MVC vs. MVVM

                                MVC      MVVM
                                                                User
        User
                  Determines                                 View
  Controller                              Passes
                                         calls to
                         View                                   Fires events
                                           ViewModel
                 State          Fires
                                                         Fires events
               queries          events

Manipulates                                Manipulates
                     Model                                    Model
MV* libraries & frameworks




          http://todomvc.com
What is KnockoutJS?

   MVVM JavaScript library
   MIT license
   No dependencies
   Supports all mainstream browsers
   Active community
Key concepts



     Declarative   Automatic UI
      bindings       refresh




    Dependency     Templating
      tracking
First steps: data binding (1)

 The magic of data-bind attribute
<span data-bind=“text: name”></span>

 Apply the bindings
ko.applyBindings(viewModel);
First steps: data binding (2)

 The syntax
  data-bind=“binding1: value1, binding2: value2,…”
 Pre-defined bindings
     text – displays text in an element (span, div, ....)
     value – for form elements (input, textarea, ...)
     click – associates a function
     visible – whether to display an element or not
     [ more on Knockout‟s website ]
Meet the observables

     var name = ko.observable(„Boyan‟);
 Functions
 Provide getters and setters
   name() is getter, name(„Peter‟) is setter
 Cache values
 Notify on changes
   name.subscribe(function(newValue) { … })
Computed observables (1)


var firstName = ko.observable(„Boyan‟);
var lastName = ko.observable(„Mihaylov‟);
var fullName = ko.computed(function() {
    return firstName() + „ „ + lastName();
});
Computed observables (2)

 Track dependencies
 Reevaluate on changes in the dependencies
 Can provide only getter or both getter and
  setter
 NOTE: Beware of circular dependencies
Observable arrays

      var names = ko.observableArray(
          ['Boyan', 'Peter', 'Elena']);

 Same as normal observables, but …
 Provide array utility functions
   push, pop, remove, slice, etc.
How to display an array?                       Indeed,
                                                how??

 Display each item in the array
 Meet the foreach binding
   Repeat the children template for each array item
   Efficient DOM manipulation - update only the
    changed parts
   Special context parameter - $parent
Extensibility: make it your way
Extend the observables

 Custom functionality associated with an
  observable
 What can we do?
   Validation
   Custom event
   …
        var age = ko.observable(10)
                .extend({ numeric: true });
Integration with other libraries

           Can we use
            Knockout
           with jQuery?




            I don‟t
                                   Yes, yes, yes!
            know…
Custom bindings (1)



<div data-bind="myBinding: data">…</div>
Custom bindings (2)

ko.bindingHandlers.myBinding = {
 // Set initial state for the DOM element
 // or register event handlers
 init: function(element, valueAccessor) { },

 // Whenever the value changes
 update: function(element, valueAccessor) { }
};
Custom bindings (3)

 Parameters
   element – the bound DOM element
   valueAccessor – a function, which returns the
    value (an observable or a plain value)
   allBindingsAccessor – a function, which returns all
    other bindings set to the element
   [ some more parameters on Knockout‟s website ]
Custom providers (1)

 Looks nice



   <div data-bind="text: name"></div>
Custom providers (2)

 Getting a bit messy

<div data-bind="text: name, visible:
  items().length > 0 && amICool(),
  customBinding: { item: 5 },
  click: showMeMoreCoolStuff"></div>
Custom providers (3)

 A complete disaster!

<div data-bind="text: name, visible:
  items().length > 0 && amICool(),
  customBinding: { item: 5, count: getGount
  }, click: showMeMoreCoolStuff, children: {
  showOnly: myChildren().length > 5,
  deleteOn: „mouseover‟ }, reset:
  „onleave‟"></div>
Custom providers (4)

   Don‟t like the data-bind attributes?
   Your markup is too messy?
   All designers in the company hate you?
   …
Custom providers (5)

 We have a solution for you!


var myBindingProvider = {
 // does a node have bindings?
 nodeHasBindings: function(node) { },
 // give me the bindings!
 getBindings: function(node, context) {}
};
Custom providers (6)

 Use id/class for attaching bindings
   Knockout.Unobtrusive plugin
 Store bindings in jQuery $.data on the
  elements
 Use more specific attributes
   e.g., data-bind-text, data-bind-image, …
Nice to read

 http://www.knockoutjs.com

 http://www.knockmeout.net

 http://groups.google.com/group/knockoutjs
Questions
Expect very soon: SharePoint Saturday!




  Saturday, June 8, 2013
  Same familiar format – 1 day filled with sessions
   focused on SharePoint technologies
  Best SharePoint professionals in the region
  Registrations will be open next week (15th)!
  www.SharePointSaturday.eu
Thanks to our Sponsors:
Diamond Sponsor:



Platinum Sponsors:




Gold Sponsors:



Swag Sponsors:

Media Partners:

More Related Content

PDF
Knockoutjs databinding
PPTX
PPTX
Knockout js
PDF
Data binding w Androidzie
PPT
Backbone.js
PDF
Backbone js
KEY
Special Events: Beyond Custom Events
PPTX
Knockoutjs databinding
Knockout js
Data binding w Androidzie
Backbone.js
Backbone js
Special Events: Beyond Custom Events

What's hot (19)

PDF
Windows 8 Training Fundamental - 1
PPTX
Jquery beltranhomewrok
PDF
Anton Minashkin Dagger 2 light
PDF
Михаил Анохин "Data binding 2.0"
PDF
"Android Data Binding в массы" Михаил Анохин
PPTX
Data binding в массы! (1.2)
PPT
JQuery New Evolution
PPTX
Client Web
PDF
Client Side MVC & Angular
PPTX
Final microsoft cloud summit - windows azure building block services
PPTX
Modular javascript
DOCX
JDBC (JAVA Database Connectivity)
PDF
Dmytro Zaitsev Viper: make your mvp cleaner
ODP
Codemotion appengine
PDF
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
PDF
Deep dive into Android Data Binding
PPTX
Planbox Backbone MVC
PDF
Windows 8 Training Fundamental - 1
Jquery beltranhomewrok
Anton Minashkin Dagger 2 light
Михаил Анохин "Data binding 2.0"
"Android Data Binding в массы" Михаил Анохин
Data binding в массы! (1.2)
JQuery New Evolution
Client Web
Client Side MVC & Angular
Final microsoft cloud summit - windows azure building block services
Modular javascript
JDBC (JAVA Database Connectivity)
Dmytro Zaitsev Viper: make your mvp cleaner
Codemotion appengine
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
Deep dive into Android Data Binding
Planbox Backbone MVC
Ad

Viewers also liked (20)

DOCX
Freshman Resume Template
PPTX
Being a generalist and being great at what you do
PDF
Kolczatka australijska rozmnażanie
ODP
Comercial da paz
PDF
FSIL-2020-Strategic-Plan
DOCX
Hipervinculo2
DOCX
Plan de educacion ambiental
PDF
HI 83f -Agir en faveur des personnes handicapées et des groupes particulièrem...
PPTX
Algoritmos Genéticos
PDF
Ficha Descriptiva Redes Sociales en la Educación
PPTX
Teori piag
PPTX
Generador de números aleatorios
PDF
The Mineral and Petroleum Resources Royalty Act, 28 of 2008 and the Mineral a...
PDF
Global Expansion Summit - London - 17 oct 2016 - Bruno Bensaid
PPTX
Becoming More Paranoid
PPSX
Medio ambiente y nuevas tecnologias
PDF
FeatureOwner
DOC
Investigar Antecedentes, Hasta La Actualidad Que Organismos De Gobierno Evalú...
PDF
Untitled Presentation
PPTX
Introducthion mvvm avec wpf
Freshman Resume Template
Being a generalist and being great at what you do
Kolczatka australijska rozmnażanie
Comercial da paz
FSIL-2020-Strategic-Plan
Hipervinculo2
Plan de educacion ambiental
HI 83f -Agir en faveur des personnes handicapées et des groupes particulièrem...
Algoritmos Genéticos
Ficha Descriptiva Redes Sociales en la Educación
Teori piag
Generador de números aleatorios
The Mineral and Petroleum Resources Royalty Act, 28 of 2008 and the Mineral a...
Global Expansion Summit - London - 17 oct 2016 - Bruno Bensaid
Becoming More Paranoid
Medio ambiente y nuevas tecnologias
FeatureOwner
Investigar Antecedentes, Hasta La Actualidad Que Organismos De Gobierno Evalú...
Untitled Presentation
Introducthion mvvm avec wpf
Ad

Similar to Bringing the light to the client with KnockoutJS (20)

PPTX
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
PPTX
MV* presentation frameworks in Javascript: en garde, pret, allez!
PDF
MVC pattern for widgets
PPTX
Fundaments of Knockout js
PDF
Integration Testing With ScalaTest and MongoDB
PPTX
The Magic of WPF & MVVM
PDF
Knockout js session
PPTX
Knockout.js
PDF
Knockoutjs
PPTX
Introduction to XAML and its features
PPTX
WPF - Controls &amp; Data
PDF
Gitter marionette deck
PDF
Developing maintainable Cordova applications
PPT
GWT MVP Case Study
PDF
Single page webapps & javascript-testing
PPT
Knockout Basics By Surekha Gadkari
PPT
KnockoutJS and MVVM
PDF
Viking academy backbone.js
PPT
Diving in the Flex Data Binding Waters
PPT
The Theory Of The Dom
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
MV* presentation frameworks in Javascript: en garde, pret, allez!
MVC pattern for widgets
Fundaments of Knockout js
Integration Testing With ScalaTest and MongoDB
The Magic of WPF & MVVM
Knockout js session
Knockout.js
Knockoutjs
Introduction to XAML and its features
WPF - Controls &amp; Data
Gitter marionette deck
Developing maintainable Cordova applications
GWT MVP Case Study
Single page webapps & javascript-testing
Knockout Basics By Surekha Gadkari
KnockoutJS and MVVM
Viking academy backbone.js
Diving in the Flex Data Binding Waters
The Theory Of The Dom

More from Boyan Mihaylov (17)

PDF
How WebAssembly is changing the Web and what it means for Angular
PDF
Crafting a robust deployment pipeline in finance
PDF
Using improv techniques for better agile teams
PDF
Web assembly brings the web to a new era
PDF
Showdown CI/CD - TeamCity
PDF
Stop the internet, i want to go offline
PPTX
Shifting to agile
PDF
Is WebAssembly the killer of JavaScript?
PDF
Lean or agile, software architecture is fragile
PPTX
Software architecture also needs agile
PPTX
Flux architecture
PPTX
AngularJS 2.0
PPTX
To SPA or not to SPA
PPTX
The AngularJS way
PPTX
Agile software architecture
PPTX
Component-driven development with AngularJS
PPTX
Identifying methods for measuring emotions
How WebAssembly is changing the Web and what it means for Angular
Crafting a robust deployment pipeline in finance
Using improv techniques for better agile teams
Web assembly brings the web to a new era
Showdown CI/CD - TeamCity
Stop the internet, i want to go offline
Shifting to agile
Is WebAssembly the killer of JavaScript?
Lean or agile, software architecture is fragile
Software architecture also needs agile
Flux architecture
AngularJS 2.0
To SPA or not to SPA
The AngularJS way
Agile software architecture
Component-driven development with AngularJS
Identifying methods for measuring emotions

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
A Presentation on Artificial Intelligence
PPTX
Machine Learning_overview_presentation.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Getting Started with Data Integration: FME Form 101
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Encapsulation theory and applications.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Reach Out and Touch Someone: Haptics and Empathic Computing
OMC Textile Division Presentation 2021.pptx
Programs and apps: productivity, graphics, security and other tools
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
A Presentation on Artificial Intelligence
Machine Learning_overview_presentation.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
A comparative study of natural language inference in Swahili using monolingua...
Encapsulation_ Review paper, used for researhc scholars
Getting Started with Data Integration: FME Form 101
SOPHOS-XG Firewall Administrator PPT.pptx
MIND Revenue Release Quarter 2 2025 Press Release
A comparative analysis of optical character recognition models for extracting...
Empathic Computing: Creating Shared Understanding
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Encapsulation theory and applications.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Diabetes mellitus diagnosis method based random forest with bat algorithm

Bringing the light to the client with KnockoutJS

  • 1. Bringing the light to the client with KnockoutJS var speaker = { name: “Boyan Mihaylov”, company: “Ebita.dk” };
  • 2. About me  Software Developer @ Ebita.dk  Software architectures / system integration  Best practices  Web trends  (Almost) Ms.c. in Computer Science @ The University of Copenhagen  Teaching assistant @ UCPH  Principles of Computer System Design
  • 3. What‟s there for today?  Why JavaScript  Why MV* patterns  What is KnockoutJS  How it works  Extensibility
  • 4. Why is JavaScript so popular?  Runs in the browser  No 3rd-party software  Considerably fast (in the latest browsers)  Low entry barriers  a.k.a. (reasonably) low learning curve  Still in the game with HTML5
  • 5. Why people hate JavaScript?  “Few” programming misunderstandings  Global variables  The proper “this” in functions  …  Browser (in)compatibility Especially the blue guy behind
  • 6. jQuery for the win!  Rich API for DOM manipulation  Traversing  Event handling  Animations  Browser compatibility
  • 7. Before & after jQuery if (document.getElementById) ... else if (document.layers) … Before else if (document.all) … $(‟#my_id‟) After
  • 8. But... Too much of a good thing is not a good thing
  • 9. The rise of MV* patterns  MV* stands for Model-View-(many variations)  MVC (Model-View-Controller)  MVVM (Model-View-ViewModel)  Separation between the data and how it is displayed
  • 10. MVC vs. MVVM MVC MVVM User User Determines View Controller Passes calls to View Fires events ViewModel State Fires Fires events queries events Manipulates Manipulates Model Model
  • 11. MV* libraries & frameworks http://todomvc.com
  • 12. What is KnockoutJS?  MVVM JavaScript library  MIT license  No dependencies  Supports all mainstream browsers  Active community
  • 13. Key concepts Declarative Automatic UI bindings refresh Dependency Templating tracking
  • 14. First steps: data binding (1)  The magic of data-bind attribute <span data-bind=“text: name”></span>  Apply the bindings ko.applyBindings(viewModel);
  • 15. First steps: data binding (2)  The syntax data-bind=“binding1: value1, binding2: value2,…”  Pre-defined bindings  text – displays text in an element (span, div, ....)  value – for form elements (input, textarea, ...)  click – associates a function  visible – whether to display an element or not  [ more on Knockout‟s website ]
  • 16. Meet the observables var name = ko.observable(„Boyan‟);  Functions  Provide getters and setters  name() is getter, name(„Peter‟) is setter  Cache values  Notify on changes  name.subscribe(function(newValue) { … })
  • 17. Computed observables (1) var firstName = ko.observable(„Boyan‟); var lastName = ko.observable(„Mihaylov‟); var fullName = ko.computed(function() { return firstName() + „ „ + lastName(); });
  • 18. Computed observables (2)  Track dependencies  Reevaluate on changes in the dependencies  Can provide only getter or both getter and setter  NOTE: Beware of circular dependencies
  • 19. Observable arrays var names = ko.observableArray( ['Boyan', 'Peter', 'Elena']);  Same as normal observables, but …  Provide array utility functions  push, pop, remove, slice, etc.
  • 20. How to display an array? Indeed, how??  Display each item in the array  Meet the foreach binding  Repeat the children template for each array item  Efficient DOM manipulation - update only the changed parts  Special context parameter - $parent
  • 22. Extend the observables  Custom functionality associated with an observable  What can we do?  Validation  Custom event  … var age = ko.observable(10) .extend({ numeric: true });
  • 23. Integration with other libraries Can we use Knockout with jQuery? I don‟t Yes, yes, yes! know…
  • 24. Custom bindings (1) <div data-bind="myBinding: data">…</div>
  • 25. Custom bindings (2) ko.bindingHandlers.myBinding = { // Set initial state for the DOM element // or register event handlers init: function(element, valueAccessor) { }, // Whenever the value changes update: function(element, valueAccessor) { } };
  • 26. Custom bindings (3)  Parameters  element – the bound DOM element  valueAccessor – a function, which returns the value (an observable or a plain value)  allBindingsAccessor – a function, which returns all other bindings set to the element  [ some more parameters on Knockout‟s website ]
  • 27. Custom providers (1)  Looks nice <div data-bind="text: name"></div>
  • 28. Custom providers (2)  Getting a bit messy <div data-bind="text: name, visible: items().length > 0 && amICool(), customBinding: { item: 5 }, click: showMeMoreCoolStuff"></div>
  • 29. Custom providers (3)  A complete disaster! <div data-bind="text: name, visible: items().length > 0 && amICool(), customBinding: { item: 5, count: getGount }, click: showMeMoreCoolStuff, children: { showOnly: myChildren().length > 5, deleteOn: „mouseover‟ }, reset: „onleave‟"></div>
  • 30. Custom providers (4)  Don‟t like the data-bind attributes?  Your markup is too messy?  All designers in the company hate you?  …
  • 31. Custom providers (5)  We have a solution for you! var myBindingProvider = { // does a node have bindings? nodeHasBindings: function(node) { }, // give me the bindings! getBindings: function(node, context) {} };
  • 32. Custom providers (6)  Use id/class for attaching bindings  Knockout.Unobtrusive plugin  Store bindings in jQuery $.data on the elements  Use more specific attributes  e.g., data-bind-text, data-bind-image, …
  • 33. Nice to read  http://www.knockoutjs.com  http://www.knockmeout.net  http://groups.google.com/group/knockoutjs
  • 35. Expect very soon: SharePoint Saturday!  Saturday, June 8, 2013  Same familiar format – 1 day filled with sessions focused on SharePoint technologies  Best SharePoint professionals in the region  Registrations will be open next week (15th)!  www.SharePointSaturday.eu
  • 36. Thanks to our Sponsors: Diamond Sponsor: Platinum Sponsors: Gold Sponsors: Swag Sponsors: Media Partners: