SlideShare une entreprise Scribd logo
1  sur  36
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:

Contenu connexe

Tendances

Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1
Kevin Octavian
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New Evolution
Allan Huang
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 

Tendances (19)

Matreshka.js
Matreshka.jsMatreshka.js
Matreshka.js
 
Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 light
 
Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"Михаил Анохин "Data binding 2.0"
Михаил Анохин "Data binding 2.0"
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
 
JQuery New Evolution
JQuery New EvolutionJQuery New Evolution
JQuery New Evolution
 
Client Web
Client WebClient Web
Client Web
 
Client Side MVC & Angular
Client Side MVC & AngularClient Side MVC & Angular
Client Side MVC & Angular
 
Final microsoft cloud summit - windows azure building block services
Final   microsoft cloud summit - windows azure building block servicesFinal   microsoft cloud summit - windows azure building block services
Final microsoft cloud summit - windows azure building block services
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)
 
Dmytro Zaitsev Viper: make your mvp cleaner
Dmytro Zaitsev Viper: make your mvp cleanerDmytro Zaitsev Viper: make your mvp cleaner
Dmytro Zaitsev Viper: make your mvp cleaner
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...SE2016 Android Mikle Anokhin "Speed up application development with data bind...
SE2016 Android Mikle Anokhin "Speed up application development with data bind...
 
Deep dive into Android Data Binding
Deep dive into Android Data BindingDeep dive into Android Data Binding
Deep dive into Android Data Binding
 
Planbox Backbone MVC
Planbox Backbone MVCPlanbox Backbone MVC
Planbox Backbone MVC
 
Vaadin7
Vaadin7Vaadin7
Vaadin7
 

En vedette

FSIL-2020-Strategic-Plan
FSIL-2020-Strategic-PlanFSIL-2020-Strategic-Plan
FSIL-2020-Strategic-Plan
Gary Jackson
 
The Mineral and Petroleum Resources Royalty Act, 28 of 2008 and the Mineral a...
The Mineral and Petroleum Resources Royalty Act, 28 of 2008 and the Mineral a...The Mineral and Petroleum Resources Royalty Act, 28 of 2008 and the Mineral a...
The Mineral and Petroleum Resources Royalty Act, 28 of 2008 and the Mineral a...
Werksmans Attorneys
 
Global Expansion Summit - London - 17 oct 2016 - Bruno Bensaid
Global Expansion Summit - London - 17 oct 2016 - Bruno BensaidGlobal Expansion Summit - London - 17 oct 2016 - Bruno Bensaid
Global Expansion Summit - London - 17 oct 2016 - Bruno Bensaid
Bruno Bensaid
 
Medio ambiente y nuevas tecnologias
Medio ambiente y nuevas tecnologiasMedio ambiente y nuevas tecnologias
Medio ambiente y nuevas tecnologias
Matias ascanio
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
Monica Bonino
 

En vedette (20)

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

Similaire à Bringing the light to the client with KnockoutJS

Introduction to XAML and its features
Introduction to XAML and its featuresIntroduction to XAML and its features
Introduction to XAML and its features
Abhishek Sur
 
WPF - Controls &amp; Data
WPF - Controls &amp; DataWPF - Controls &amp; Data
WPF - Controls &amp; Data
Sharada Gururaj
 

Similaire à Bringing the light to the client with KnockoutJS (20)

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

Plus de Boyan Mihaylov

Identifying methods for measuring emotions
Identifying methods for measuring emotionsIdentifying methods for measuring emotions
Identifying methods for measuring emotions
Boyan Mihaylov
 

Plus de Boyan Mihaylov (17)

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

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

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: