O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

Knockout js

320 visualizações

Publicada em

Knockout JS offered by Syed Awase Khirni, CGI Bangalore, Open House in Bangalore, Hyderabad.

Publicada em: Software
  • Seja o primeiro a comentar

Knockout js

  1. 1. Code Focused Training Syed Awase Khirni Syed Awase earned his PhD from University of Zurich in GIS, supported by EU V Framework Scholarship from SPIRIT Project (www.geo-spirit.org). He currently provides consulting services through his startup www.territorialprescience.com and www.sycliq.com {>}GROUND UP JavaScript MVVM Framework
  2. 2. Code Focused Training Why NOT JQUERY? • Jquery isn’t usually used for complex web apps •No easy way for the UI and the data to communicate •More complex way to interact with the data model •Client Side validations and AJAX calls •DOM Manipulation Library •Limited to Form and UI Interactions © Syed Awase 2015-16 - KnockOut Ground Up! 2
  3. 3. What is KnockOut? • Knockout.js is a JavaScript library that enables you to declaratively bind elements against model data with two-way updates happening automatically between your UI and model. • KO is a data-binding library while AngularJS is a full-framework. • Angular uses routes, directives and services , while KO does not. • JavaScript MVVM Framework • MVVM – Model-View-ViewModel • Model – Objects in your business domain • View – User Interface that is visible to the user • ViewModel – code representing data/operations on a UI (Presentation Concerns) • Complimentary to other JavaScript Frameworks • E.g. Jquery, CoffeScript, Prototype, etc. © Syed Awase 2015-16 - KnockOut Ground Up! 3
  4. 4. Code Focused Training Knockout © Syed Awase 2015-16 - KnockOut Ground Up! 4 knockout-3.4.0.js http://knockoutjs.com/downloads/knockout-3.4.0.js Referencing in your application Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, Edge, others) http://www.knockmeout.net/
  5. 5. Code Focused Training © Syed Awase 2015-16 - KnockOut Ground Up! 5 Knockout “A java script library that helps you to create rich, responsive display and editor UI with a clean underlying data model. Anytime you have section of UI that update dynamically, KO can help you implement it more simply and easily maintainable” Client side data binding library for building data-aware web applications
  6. 6. Why Knockout? • Developing a complex and dynamic data-driven web application can be a challenging task. • Keeping a user interface in sync with the underlying data normally involves wiring up a number of event handlers to broker information between the various elements and the data whenever any actions are performed by a user or when new data is loaded. © Syed Awase 2015-16 - KnockOut Ground Up! 6
  7. 7. Code Focused Training © Syed Awase 2015-16 - KnockOut Ground Up! 7 DECLARATIVE BINDING Easily associate DOM elements with model data using a concise readable syntax AUTOMATIC UI REFRESH When your data model’s state changes, your UI updates automatically TEMPLATING Quickly generate sophisticated, nested Uis as a function of your model data UI DEPENDENCY TRACKING Implicitly set up chains of relationships between model data, to transform and combine it
  8. 8. Code Focused Training Traditional UI Development MODEL VIEW © Syed Awase 2015-16 - KnockOut Ground Up! 8 DOMAIN OBJECTS UI Layout Code behind Update Fetch data
  9. 9. Code Focused Training Traditional UI Development Constraints • Difficult to test • Encourages using UI as a data storage • Complex classes and huge amount of code • No Code sharing • Very strong dependency between UI and Logic • Redeisgn requires a lot of effort Why MVVM © Syed Awase 2015-16 - KnockOut Ground Up! 9 Clear responsibilities between the developers and designers
  10. 10. Code Focused Training Knockout Architecture © Syed Awase 2015-16 - KnockOut Ground Up! 10 MODEL BUSINESS LOGIC AND DATA VIEW MODEL USER INTERFACE VIEW MODEL PRESENTATION LOGIC JAVASCRIPT REMOTING INSTANT NOTIFICATIONS TWO WAY DATABINDING COMMANDS EXECUTION
  11. 11. Code Focused Training Design Patterns and Architectural Guide © Syed Awase 2015-16 - KnockOut Ground Up! 11 Design Patterns are essentially time tested solutions to recurring design problems. SOME DESIGN PATTERNS USED FOR KNOCKOUT MVVM OBSERVER JAVASCRIPTCLOSURE MODULEPATTERN
  12. 12. Code Focused Training Presentation Design Pattern © Syed Awase 2015-16 - KnockOut Ground Up! 12 MVVM MVP MVC Model-View-ViewModel Model-View-Presentation Model-View-Controller UI Centric Design Patterns SEPARATION OF CONCERNS CODE REUSABLITY UNIT TESTING SPA DECOUPLING
  13. 13. Code Focused Training MVC © Syed Awase 2015-16 - KnockOut Ground Up! 13 VIEW CONTROLLER MODEL Passes Calls to Manipulates Fires Events User Input • Controller contains the logic that alters the model depending on the action triggered by UI. • View is a composite implementation, A view can switch controllers or a single controller can be used by multiple views. View subscribes to changes done to the model • controller manipulates the data but asserting the changes from a view perspective
  14. 14. Code Focused Training MVP © Syed Awase 2015-16 - KnockOut Ground Up! 14 VIEW PRESENTER MODEL Passes Calls to Manipulates Fires Events User Input • Controller is replaced by Presenter , it presents the changes done in model back to view. • Presenter here takes the responsibility of not only manipulating model but also updating the view. •MVP Variations •Supervising controller : uses a controller both to handle input response but also to manipulate the view to handle more complex view logic. It leaves simple view behavior to the declarative system, intervening only when effects are needed that are beyond what can be achieved declaratively • Passive View handles this by reducing the behaviour of UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view. Allows testing to be focused on the controller with little risk of the problem in the view. Updates
  15. 15. Code Focused Training Real World MVC • Controllers are “almost” not reusable • Controllers are large • View is very tight to it’s controller • Controllers are hard to unit test • © Syed Awase 2015-16 - KnockOut Ground Up! 15 MVC VIEW CONTROLLER VIEW MODEL
  16. 16. Code Focused Training MVVM © Syed Awase 2015-16 - KnockOut Ground Up! 16 VIEW CONTROLLER VIEW MODEL MODEL VIEWS UNIT TESTS VIEWMODELS MODEL DB ENTITIES Binding, Commands, Data Templates User Controls
  17. 17. The Model • The applications stored data • Independent of the UI • Ajax calls to read/write to and from the stored data © Syed Awase 2015-16 - KnockOut Ground Up! 17
  18. 18. The View Model • Code representation of the data and operations • Not the UI itself • Pure javascript • Holds unsaved data
  19. 19. The View • Visible UI • Displays ViewModel Information • Updates when the State changes • HTML Document with Declarative Bindings + CSS3 Styling.
  20. 20. Code Focused Training MVVM • View Model does not need a reference to a VIEW • ViewModel coordinates with one or more models, exposes properties for the view to bind to. • views know about the ViewModel but not the model • ViewModel knows about the Model but not the View • Model Knows about itself • View binds to properties in the ViewModel • .Changes to properties in the ViewModel automatically propogate to the View – no additional code required • Data Changes made in the ViewModel, never the View • More testable than MVC or MVP © Syed Awase 2015-16 - KnockOut Ground Up! 20 VIEW VIEWMODEL MODEL Passes Calls to Manipulates Fires Events User Input
  21. 21. Code Focused Training MVVM BENEFITS • Modularity • Decoupling components • Allows each component to be versioned independently • Flexibility • Multiple views for one Model (web front end, desktop front end, mobile front end, etc) • Replace one component (replace data storage from flat file to database) • Maintainability • Only change one component where bug exists, less risk in late changes • Testability • Each component communicates through contract so each component can be unit-tested independently VIEW MODEL ACTS AS A COMPLETE MIRROR OF THE VIEW © Syed Awase 2015-16 - KnockOut Ground Up! 21 VIEW VIEWMODEL MODEL BUSINESS LOGIC PRESENTATION LOGIC UI LOGIC NOTIFICATION DATABINDING
  22. 22. Code Focused Training View • UserControl based • XAML • Minimal code behind • Data Context set to the associated VIEWMODEL • No Event Handlers • Databinding pushes the changes from the ViewModel to View and from View to ViewModel • Loosely coupled, can easily replace the view without affecting the view model © Syed Awase 2015-16 - KnockOut Ground Up! 22 ViewModel • Implements INotifyPropertyChanged • Expose Icommand • Handle Validation • Adapter class between the View and the Model • Listen to the Model’s events • Testable Model • Event Based mechanism to signal changes to the ViewModel VIEWMODEL VIEW MODEL
  23. 23. Code Focused Training MODEL • Non-visual classes that encapsulate the application’s data and business logic • Can’t see ViewModel or View • Should not contain any use case- specific or user-task-specific behaviour or application logic • Notifies Other components of any state changes • May provide data validation and error reporitng. VIEW MODEL •Non-visual class encapsulates the presentation logic required •Can’t see View ( no direct references) •Coordinates the View’s interactions with the model •May provide data validation and error reporting •Notifies the view of any state changes © Syed Awase 2015-16 - KnockOut Ground Up! 23
  24. 24. Code Focused Training VIEW •Visual element defines the controls and their visual layout and styling •Can see all other components •Defines and handles UI visual behaviour, such as animations or transitions •Code behind may contain code that requires direct references to specific UI controls View  ViewModel Interaction Ways Data Binding Commands Notifications © Syed Awase 2015-16 - KnockOut Ground Up! 24
  25. 25. Code Focused Training MVP vs.MVC vs.MVVM MVP(Presenter) MVC(Controller) MVVM(ViewModel) View Communicates with the presenter by directly calling functions on an instance of the presenter View sends input events to the controller via a callback or registered handler View binds directly to the View Model The presenter communicates with the view by taking to an interface implemented by the view View receives updates directly from the model without having to go through the controller Changes in view are automatically reflected in ViewModel and viceversa Use where binding via a data context is not possible Use where the connection between the view and the rest of the program is not always available Use where binding via a data context is possible. © Syed Awase 2015-16 - KnockOut Ground Up! 25 e.g. Windows Forms e.g. SmallTalk, ASP.NET MVC e.g. WPF, KO,AngularJS
  26. 26. Code Focused Training MVVM © Syed Awase 2015-16 - KnockOut Ground Up! 26 • Enable UI Unit Testing • WPF Line of Business Application • Layers represent Separation of concerns and decoupling • Enables designer – developer workflow • Is a natural pattern given WPF’s rich data binding that promotes loose coupling • Takes full advantage of WPF’s DataTemplates and Commands • UI (view) can be swapped out without touching the UI code
  27. 27. Code Focused Training MVVM Advantages • Separation of concerns • Can use unit tests • Designers and developers can work synchronously • Easy to redisgn the UI • Can share code easily Disadvantages •Harder to debug •May affect performance •More files to serve the architecture © Syed Awase 2015-16 - KnockOut Ground Up! 27
  28. 28. Code Focused Training DataBinding (State) • Process that establishes a connection between the application UI and application logic • When the data changes its value, the elements that are bound to the data reflect changes automatically • Direction of data flow • One Time: binding update the target with the source data when binding is created • One Way bindings update the target with the source data when the binding is created, and any time the data changes. This is the default mode. • Two Way bindings update both the target and the source when either changes © Syed Awase 2015-16 - KnockOut Ground Up! 28 Dependency Property Property VIEW VIEWMODEL Dependency Object Object BINDING TARGET BINDING SOURCE Provides an easy and efficient method to connect information to a user interface that displays the data
  29. 29. Code Focused Training Data Binding Options • Directions of the data flow •One way • Two way • One time • One way to Source •What triggers source updates (LostFocus, PropertyChanged, Explicit, …) •Bind to Objects, Collections, UI Elements • Path, Value Converters, Async, Fallback, StringFormat One Time: the data is set when binding is intialized-mostly used in ReadOnly mode OneWay: Updates the data from source to target, so if source changes the target is notified. Two way: Updates data from source to taget and vice-versa, so if the source changes the target is notified or vice versa © Syed Awase 2015-16 - KnockOut Ground Up! 29
  30. 30. ONE-TIME DATA BINDING • When you request one-time data binding, the run-time, using the data source and the specified path, retrieves the source value and initializes the specified target property to that value. • No change occurs subsequently when the source or the target property value is changed. • Two Special Cases – When the DataContext of an element changes, effectively, the data source has changed and therefore the binding performs another one-time transfer – In many cases, the DataContext refers to a collection of objects. When the current object for a collection changes, the databinding performs a one-time transfer. © Syed Awase 2015-16 - KnockOut Ground Up! 30
  31. 31. ONE-WAY DATA BINDING • On request, the runtime retrieves the source value and initializes the specified target property to that value. • Each time the source value changes the data binding retrieve the new value and reinitialize the target property
  32. 32. TWO-WAY DATA BINDING • On request, the runtime retrieves the source value and initializes the specified target property to that value. • Each time the source value changes, the data binding retrieves the new values and reinitializes the target property. • Additionally, when the target property changes value- e.g. when the user types into an edit control – the data binding retrieves the new target property value and propagates it back to the source. • Default type of data binding.
  33. 33. TRANSFORMERS • Allows you to convert a value from one form to another as it propogates to and from a data source to a target. • A transformer is used to convert a value from its internal representation to a unique displayed value. • A transformer can also be used as a data type converter. • A transformer also receives the culture information for the User Interface as one of its parameters, which can be used to tailor the presented user interface to suit the current culture of the user.
  34. 34. Code Focused Training Commands (Behaviour) •Provide a way to represent actions or operations that can be easily bound to controls in the UI •Encapsulate the actual code that implements the action or operation •Examples: Button Click, List selection changed • OnPropertyChanged method is required to notify binding target properties with change in source • Observable Collection needed for binding lists source •Implementing InotifyPropertyChanged and INotifyCollectionChanged interface © Syed Awase 2015-16 - KnockOut Ground Up! 34
  35. 35. Code Focused Training Data Templates • Converts non-visual data into its visual representation •Defines how a view model will be rendered or can modify its default visual representation without changing the underlying object itself or the behavior of the control that is used to display it. Simple datatemplate using HTML Listbox Control © Syed Awase 2015-16 - KnockOut Ground Up! 35
  36. 36. Code Focused Training Observer Pattern • A behavioral pattern used to assure consistency between objects • Used to establish relationship between objects at runtime not compile time • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically • Object that changes is called “Subject” • Object that receives updates is called “Object” • Two Approaches • Pull model: Observer invokes method requesting data • Push model: subject passes data to observer as argument at update() Similar to NewsPaper Subscription Publisher publishes and subscribers read Once subscribers unsubscribe, subscribers won’ Once subscribers subscribe again they get to read Publishers are Subject and Subscribers are Observer © Syed Awase 2015-16 - KnockOut Ground Up! 36
  37. 37. Code Focused Training Observer Pattern Benefits • Objects are loosely coupled with each other but still communicate properly • Observers can be added/removed at any time • Subject and Observer can belong to different abstraction layers • Subject does not need to know the concrete class of an observer, just that each observer implements the update interface • Observers can be added without modifying the subject Usage • Used when there is one to many relationship between object such as if one object is modified, its dependent objects are to be notified automatically • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. © Syed Awase 2015-16 - KnockOut Ground Up! 37
  38. 38. Code Focused Training IIFE • A javascript design pattern which produces a lexical scope, using Javascript’s function scoping. • IIFE is used to avoid variable hoisting from withinblocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined with the function • Emulate privacy © Syed Awase 2015-16 - KnockOut Ground Up! 38
  39. 39. Code Focused Training Module Pattern • Help in keeping the units of code for a project both cleanly separated and organized. • originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering. • The module pattern encapsulates “privacy”, state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer’s interface © Syed Awase 2015-16 - KnockOut Ground Up! 39
  40. 40. Code Focused Training Revealing Module Pattern • Advantages : • More consistent syntax. • Clear outline of functions and variables which can be accessed publicly which eases readability. • Disadvantages: • If a private function refers to a public function, that public function cannot be overridden if a patch is necessary. The private function will continue to refer to the private implementation and the pattern does not apply to public members, only to functions • Public object members which refer to private variables are also subject to the no-patch rule © Syed Awase 2015-16 - KnockOut Ground Up! 40
  41. 41. Code Focused Training Singleton Pattern • It restricts instantiation of a class to a single object. • It can be implemented by creating a class with a method that creates a new instance of the class if one doesnot exist. • In the event of an instance already existing. It simply returns a reference to that object. • They serve as a shared resource namespace which isolate implementation code from global namespace so as to provide a single point of access for functions. © Syed Awase 2015-16 - KnockOut Ground Up! 41
  42. 42. Code Focused Training Observer Pattern • A design pattern where an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state. • When a subject needs to notify observers about something interesting happening. It broadcasts a notification to the observers ( which can include specific data related to the topic of the notification). • When we no longer wish for a particular observer to be notified of changes by the subject they are registered with, the subject can remove them from the list of observers. • Encourages us to think hard about the relationships between different parts of our application. • Help in identifying the layers containing direct relationships which could instead be replaced with sets of subjects and observers. • Modular application development, more loosely coupled block to improve code management and reusability. • Dynamic relationships can exist between observers and subjects. • Sometimes, difficult to obtain guarantees that particular parts of our applications are functioning as we may expect. © Syed Awase 2015-16 - KnockOut Ground Up! 42
  43. 43. Code Focused Training KO DEBUGGING TOOLS © Syed Awase 2015-16 - KnockOut Ground Up! 43 KO CONTEXT DEBUGGER https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof?hl=en GLIMSE FROM NUGET PACKAGE MANAGER
  44. 44. Code Focused Training KO Core © Syed Awase 2015-16 - KnockOut Ground Up! 44
  45. 45. Code Focused Training Activating Knockout • Include knockout.js core files using script include tags • Apply Binding using ko.applyBindings • The first parameter says what viewModel object to use with declarative bindings, which is activated. • Optionally, it takes a second parameter to define which part of the document to search for data-bind attributes. Useful in the case of multiple viewModels and associate each viewModel with a different region of a page. © Syed Awase 2015-16 - KnockOut Ground Up! 45 Step 2: Include ko.applyBindings(ViewModel) should be same Step 1: Include knockout.js resource
  46. 46. Code Focused Training 3 Types of KO Observables • Used for view model propertiesObservable • Used for collections Observable arrays • Encapsulate one or more other observables Dependent observables
  47. 47. KO Observables • JavaScript functions – Not all browsers support javascript getter and setter functions • Internally Knockout JS’s binding observe the Observables • Used to detect and respond to changes on an object • Allows for 2 way data binding, by notifying subscribers about the changes and can automatically detect dependencies. • Can be subscribed to © Syed Awase 2015-16 - KnockOut Ground Up! 47
  48. 48. Code Focused Training Reading and Writing Observable Read • Call the observables current value, with no parameters. Write • To write a new value to the observable, call the observable and pass the new value as a parameter. Write Multiple Properties • To write value to multiple observable properties on a model object using chaining.
  49. 49. Code Focused Training Explicitly subscribing to observables • To register your own subscriptions to be notified of changes to observables, use subscribe function • Subscribe function takes in 3(three) parameters • Callback – the function that is called whenever the notification happens • Target – defines the value of this in the call back function • Event- name of the event to receive notification for © Syed Awase 2015-16 - KnockOut Ground Up! 49 Advanced Concept
  50. 50. Code Focused Training Explicitly subscribing to observables • Dispose: this function is used to terminate a subscription if you wish to. First capture the return value as a variable © Syed Awase 2015-16 - KnockOut Ground Up! 50 Advanced Concept • beforeChange Event: if you want to be notified of the value of an observable before it is about to be changed.
  51. 51. Code Focused Training Explicitly subscribing to observables • Dispose: this function is used to terminate a subscription if you wish to. First capture the return value as a variable © Syed Awase 2015-16 - KnockOut Ground Up! 51 Advanced Concept • beforeChange Event: if you want to be notified of the value of an observable before it is about to be changed.
  52. 52. Code Focused Training Observables Notify subscribers: notify • Used to notify observable’s subscriber on write, even if the value is the same. • When writing to an observable that contains a primitive value( number, string, boolean or null) the dependencies of the observersable are normally ONLY notified if the value actually changed. Delay/Suppress Change Notification :rateLimit • An observable notifies its subscribers immediately, as soon as it’s changed. But if the observable is changed repeatedly or triggers expensive updates, we may get better performance by limiting or delaying the observable’s change notifications. © Syed Awase 2015-16 - KnockOut Ground Up! 52
  53. 53. Code Focused Training KO Observable Arrays • Used with Collections, They detect changes to the collection of things. • Useful in many scenarios when displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed. An observableArray tracks which objects are in the array, not the state of those objects •Use Knockout array methods •Cross browser •Dependency Tracking •Clean Syntax
  54. 54. Code Focused Training Prepopulating an ObservableArray • Developers can populate the observable array by passing in some initial items as an array to the constructor © Syed Awase 2015-16 - KnockOut Ground Up! 54
  55. 55. Code Focused Training Reading an observableArray • An observableArray is an observable whose value is an array. • The underlying array can be invoked as a function with no parameters. • native javascript array functions can be used to operate on the underlying array. • indexOf: returns an index of the first array item that equals your parameter. • Modify the contents of an array. KO’s methods automatically trigger the dependency tracking mechanisms so that all registered listeners are notified. • Push,Splice ,pop,shift, unshift,reverse, sort, splice © Syed Awase 2015-16 - KnockOut Ground Up! 55
  56. 56. Code Focused Training Observable array methods • Returns zero-based index of itemList.indexOf(“value”) • Returns items between start/end indexList.slice(2,4) • Adds new item to endList.push(“value”) • Removes last itemList.pop() • Inserts item at beginningList.unshift(“value”) • Reverses orderList.reverse() • Sorts the itemsList.sort() • Removes specified itemList.remove(item) • Removes all itemsList.removeAll()
  57. 57. Code Focused Training Manipulating an ObservableArray Push(value) • Adds a new item to the end of the array © Syed Awase 2015-16 - KnockOut Ground Up! 57 Pop(value) • Removes the last value from the array and returns it Unshift(value) • Inserts a new item at the beginning of the array
  58. 58. Code Focused Training Manipulating an ObservableArray Shift() • Removes the first value from the array and returns it © Syed Awase 2015-16 - KnockOut Ground Up! 58 Reverse(value) •Reverses the order of the array and returns the observableArray( not the underlying array) Sort() • sorts the array contents and returns the observableArray
  59. 59. Code Focused Training Manipulating an ObservableArray Splice() • Removes and returns a given number of elements starting from a given index. © Syed Awase 2015-16 - KnockOut Ground Up! 59 Remove • removes all the values that equal someItem and returns them as an array RemoveAll • removes all values that equal a value and returns them as an array.
  60. 60. Code Focused Training Manipulating an ObservableArray Destroy() • Finds any objects in the array that equal someItem and gives them a special property called _destroy with value true © Syed Awase 2015-16 - KnockOut Ground Up! 60 DestroyAll() • Finds any objects in the array that are equal to a given object, and gives them a special property called _destroy with a value true Delay/Suppress:rateL imit • Similar to delay and suppressing in observable, they are used to improve performance by limiting or delaying change notifications.
  61. 61. Code Focused Training Dependent ObservablesEncapsulate one or more observables Need to manage this pointer
  62. 62. Code Focused Training Computed Observables • Functions that are dependent on one or more other observables and will automatically update whenever any of these dependencies change. • Evaluator function is called once each time any of its dependencies change and whatever value it returns will be passed on to the observers such as UI elements or other computed observable © Syed Awase 2015-16 - KnockOut Ground Up! 62
  63. 63. Code Focused Training Pure Computed Observables • If your computed observable simply calculates and returns a value based on some observable dependencies, then it’s better to declare it as a ko.pureComputed • Its evaluator does not directly modify other objects or state. • KO can more efficiently manage its re-evaluation and memory use. • KO will automatically suspend or release it if no other code has an active dependency on it. © Syed Awase 2015-16 - KnockOut Ground Up! 63
  64. 64. Code Focused Training PureComputed Observable Notify extender • When a computed observable returns a primitive value ( a number, string, boolean or null), the dependencies of the observable are normally only notified if the value actually changed. • Use built-in notify extender to ensure that a computed observable’s subscribers are always notified on an update, even if the value is the same. Ratelimit extender • As the dependencies change, a computed observable updates and notifies its subscribers immediately. • To improve the performance by limiting or delaying the computed observable’s updates and notifications. © Syed Awase 2015-16 - KnockOut Ground Up! 64
  65. 65. Code Focused Training Determining if Computed Observable • To check if it is a computed observable. • ko.isComputed  returns true or false if it is computed Observable or not • Ko.isObservable  returns true for observables, observable arrays and all computed observables. • Ko.isWritableObservable  returns true for observables, observable arrays, writable computed observables • If you ONLY need to use the compound full name in the UI • KO will create a computed observable internally in order to detect what observables the expression depends on and will automatically dispose it, when the associated elements are removed. © Syed Awase 2015-16 - KnockOut Ground Up! 65 UI Computed Observables
  66. 66. Code Focused Training Constructing a computed observable © Syed Awase 2015-16 - KnockOut Ground Up! 66 • evaluator – A function that is used to evaluate the computed observable’s current value • targetObject – if given, defines the value of this whenever KO invokes your callback functions. • options – An object with further properties for the computed observable A single parameter form for creating a computed observable accepts a Javascript Object with any of the following properties • read- Required. A function that is used to evaluate the computed observable’s current value • write- Optional, if given makes the computed observable writable. This is a function that receives values that other code is trying to write to your computed observable. It’s up to you to supply custom logic to handle the incoming values, typically by writing the values to some underlying observable(s)
  67. 67. Code Focused Training Constructing a Computed Observable © Syed Awase 2015-16 - KnockOut Ground Up! 67 Constructs a pure computed observable using the given evaluator function and optional object to use for this. Unlike ko.computed, this method doesn’t accept an options parameter. Constructs a pure computed observable using an optionsobject. This accepts the read, write, and owner options
  68. 68. Using a computed Observable function Description Dispose() Manually disposes the computed observable, clearing all subscriptions to dependencies Extend(extenders) Applies the given extenders to the computed observable getDependenciesCount() Returns the current number of dependencies of the computed observable getSubscriptionsCount([event]) Returns the current number of subscripts isActive() Returns whether the computed observable may be updated in the future. Peek() Returns the current value of the computed observable without creating a dependency Subscribe(callback [,callbackTarget, event]) Registers a manual subscription to be notified of changes to the computed observable. © Syed Awase 2015-16 - KnockOut Ground Up! 68
  69. 69. Determining the observable type Function Description Ko.isObservable Returns true for observables, observable arrays, and all computed observables Ko.isWritableObservable Returns true for observables, observable arrays, and writable computed observables Ko.isComputed Returns true for all computed observables Ko.isPureComputed Returns true for pure computed observables
  70. 70. Using the computed context Function description isInitial() A function that returns true if called during the first ever evaluation of the current computed observable, or false otherwise. For pure computed observables isInitial() is always undefined. getDependenciesC ount() returns the number of dependencies of the computed observable detected so far during the current evaluation
  71. 71. Built-in Bindings: 4.Template © Syed Awase 2015-16 - KnockOut Ground Up! 72 •Traditional JavaScript template in <script> tag JavaScript Templates •Template-less, comment-based syntax Containerless Control flow (Annonymous)
  72. 72. Why use Data Binding? • KO’s data binding system gives us an extremely powerful and efficient way to bind data between the model and the view. • “data-bind” attribute is the glue that it holds it all together. – Comma separated options – Completely valid with HTML5 as it is a “data” attribute – Many types of declarative bindings • Jquery that does great things like manipulating the DOM, BUT they really lack the ability for the model to send the data to UI.
  73. 73. Binding Values • Can be a value, variable, literal or any type of JavaScript expression
  74. 74. Code Focused Training KO Bindings  Built-in Bindings Text and Appearance Forms Control Flow Templates  Custom Binding  indispensible tools for any knockout developer and is one of the best extensibility points that knockout has © Syed Awase 2015-16 - KnockOut Ground Up! 75
  75. 75. Built-in Bindings: 1.Text and Appearance © Syed Awase 2015-16 - KnockOut Ground Up! 76 • Toggle visibility of the DOM ElementVisible • Text value of DOM elementText • Raw HTML of DOM elementhtml • CSS class(es) of DOM elementCss • Raw style attribute of DOM elementStyle • Any arbitrary attribute of DOM elementAttr
  76. 76. The visible binding • Causes the associated DOM element to become hidden or visible according to the value you pass to the binding.
  77. 77. The visible binding • Using functions and expressions to control element visibility – We can use javascript function or arbitrary javascript expression as the parameter value.
  78. 78. The text binding • Causes the associated DOM element to display the text value of your parameter • Useful with elements like <span> or <em> that traditionally display text, but technically you can use it with any element. Usually used in <span> tags
  79. 79. The text binding • Without a container element – Sometimes you may want to set text using KO without including an extra element for the text binding.
  80. 80. The html binding • Causes the associated DOM element to display the HTML specified by your parameter • Useful when values in your view model are actually strings of HTML markups that you want to render. Since this binding sets your element’s content using innerHTML, you should be careful not to use it with untrusted model values, because that might open the possibility of script injection attack.
  81. 81. The css binding • Adds or removes one or more named css classes to the associated DOM element. • The below example will apply the css class profitWarning whenever the currentProfit value dips below zero and remove that class when ever it goes above zero
  82. 82. The css binding (with dynamic classes) • Apply the css class profitPositive when the currentProfit value is positive, otherwise it will apply the profitWarning CSS class.
  83. 83. The style binding • Adds or removes one or more style values to the associated DOM element. • Useful to highlight some value in red if it becomes negative, or to set the width of a bar to match a numerical value that changes. • In the example below, the element’s style.color property to red whenever the currentProfit value dips below zero and to black whenever it goes above zero http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html
  84. 84. The attr binding • Provides a generic way to set the value of any attribute for the associated DOM element. • Useful when we need to set the title attribute of an element, the src of an img tag or the href of a link based on values in your view model, with the attribute value being updated automatically whenever the corresponding model property changes.
  85. 85. Built-in Bindings: 2.FORMS © Syed Awase 2015-16 - KnockOut Ground Up! 87 • Handler invoked when DOM element clickedClick • Handler invoked for arbitrary event on DOM elementEvent • Handler invoked when form submittedSubmit • DOM element enabled if trueEnable • DOM element disabled if trueDisable • Any arbitrary attribute of DOM elementValue • Attached to checkbox and radio buttonchecked • Collection of elements in dropdown or multi-selectoptions • Currently selected item(s) of dropdown or multi-selectselectedOptions • Ensures DOM element has “name” attributeuniqueName
  86. 86. Click Binding • Click binding adds an event handler so the chosen javascript will be invoked when the associated element is clicked. • Usually used with buttons, input and links
  87. 87. Event Binding • Event binding allows you to add an event handler for a specific event • Used for events like keypress, mouseover and mouseout • You can also access the DOM event object associated with your event.
  88. 88. Submit Binding • Adds an event handler so that a specific function will be invoked when the DOM element is submitted • Obviously this usually done using a form element
  89. 89. Enable and Disable Binding • The enable binding causes the associated DOM element to only be enabled when the value is true • Disable does the opposite and is disabled when true
  90. 90. Value Binding • The value binding is associated with a property in the view model. • This is usually used on input, select and textarea fields : 2 way data binding.
  91. 91. Other Bindings • hasFocus – links a DOM element’s focus state with a viewmodel property • Checked – links checkable form control to a view model property • Options- shows which options should appear in a drop-down
  92. 92. Binding Contexts • Object that holds data that can be easily referenced from your bindings. • KO creates and manages a context hierarchy • The viewModel parameter is the root level • Each control flow binding creates a new child binding context that refers to the nested model data.
  93. 93. Parent Binding Contexts • Current data bound item$data • Item from parent binding context$parent • Array containing all parent bindings contexts$parents • Item at the top of the binding$root
  94. 94. $parent • Context immediately outside the current context • In the “root” context, this is undefined- the root has no parent • $parent – array of all parent view models • $parents[0] – aren’t context (same as $parent) • $parents[1]- Grandparent context • $parents[2]-Great-grandparent
  95. 95. $root • Main view model object in the root context • Topmost parent context • Usually the object passed to ko.applyBindings • Equivalent to $parents[$parents.length-1]
  96. 96. $component • If you are in a component context, it refers to that components view model • Component-specific equivalent to $root • If nested then refers to the closest component
  97. 97. $data • View model object in the current context • In $root context, $data and $root are the same • Useful to reference the view model itself.
  98. 98. $index • Only available within foreach bindings • Zero-based index of the current array entry • Observable and updated
  99. 99. $parentContext • The binding context object at the parent level • Different from $parent • Can be used to access an index value of an outer foreach item
  100. 100. Others • $rawData – Raw view model value in the current context. Usually the same as $data. • $componentTemplateNodes- Within the context of a particular component template. An array that holds any DOM nodes that are passed to the component. • $context – Current binding context object • $element – the element DOM object of the current binding
  101. 101. Built-in Bindings: CONTROL FLOW © Syed Awase 2015-16 - KnockOut Ground Up! 105 • Executes if condition is trueif • Executes if condition is falseifnot • Executes for each item in collectionForeach • Executes for object specified (child models)With
  102. 102. The if binding • The if binding causes a section of markup to appear in your document ( and to have its data-bind attributes applied), only if a specified expression evaluates to true • Physically adds or removes the contained markup in the DOM and only applies bindings to descendants if the expression is true. • If plays a similar role to the visible binding. • With visible, the contained markup always remains in the DOM and always has its data-bind attributes applied – the visible binding just uses CSS to toggle the container element’s visibility.
  103. 103. The if binding • “if” binding without a container element
  104. 104. Iterating over an array
  105. 105. Add/remove records
  106. 106. KO Data Features © Syed Awase 2015-16 - KnockOut Ground Up! 110
  107. 107. With Binding • Creates a new binding context • Descendant elements are bound in the context of a specified object • You can also use with other control flow bindings such as if and ifnot.
  108. 108. Component Binding • Injects a specific component into an element • Optional param
  109. 109. KO Utilities and Data Features KO Utilities • Ko.utils.arrayFilter • Ko.utils.arrayFirst • Ko.utils.arrayForEach • Ko.utils.arrayIndexOf • Ko.utils.arrayMap • Ko.utils.arrayPushAll • Ko.utils.arrayRemoveItem • Ko.utils.compareArrays • Ko.utils.unwrapObservable Data Features • Ko.toJS() – JavaScriptObject with just data and no knockout constructs • Ko.toJSON() – Produces JSON string representing view model’s data (calls ko.toJS() internally)
  110. 110. Templating? • Templating gives us a simple and elegant way to build professional looking user interface structures • Templating Type –Native templating –String Based Templating
  111. 111. Native Templating • Supports control flow bindings ( foreach, if, with) • Captures HTML markup and uses it as a template to render against arbitrary data items • Built into knockout and no external libraries are needed.
  112. 112. String-Based Templating • Connects Knockout to a 3rd party engine • Knockout can pass model values to the external template engine • Knockout injects the resulting markup string into the document.
  113. 113. Binding parameters Name ID of the element with the template you wish to render Nodes Array of DOM nodes to use as a template (non-observable array) Data Object to supply the data to be rendered If If provided, the template will only render if true Foreach Renders a template in foreach mode As Defines alias for items being rendered afterRender, afterAdd, beforeRemove Callbacks to invoke against rendered DOM elements
  114. 114. Dynamic Choosing • If you have multiple names templates, you can pass an observable for the name option. • As the value is updated, the element contents will be re- rendered using the correct template • You could also pass a callback function to choose the correct template.
  115. 115. Underscore Template Engine
  116. 116. Custom Bindings • The most important extensibility functionality of knockoutjs
  117. 117. Custom Bindings • When we want more control and flexibility over elements and observables used. • To create our own interactive controls, we use custom binding. • All the bindings available in knockoutJS are the sub properties of a “ko.bindingHandlers” object. • Create a custom binding – Add a property with your custom binding name – Assign an object with two call back functions.
  118. 118. Custom bindings init – Init callback: executed when the binding is applied the very first time. The initial setup necessary for the custom binding such as attaching events, setting up the initial state for variable and so on. – The init callback function will be called only when the binding is applied update • Update callback: called whenever the associated observable is changed. • While binding your custom binding handler with the element, if you have associated / assigned an observable to your custom binding handler then update call back will be executed whenever you change the associated/assigned observable.
  119. 119. Custom bindings (Parameters of callback functions) Tag Description Element DOM element on which our custom binding is applied ValueAccessor The javascript function that will return the value/assigned/associated with the binding. Use “ko.unwrap”utility function to get the value assigned allBindingAccessor The JavaScript function that will return all the values assigned/associated with all the bindings bound with the current DOM. Suppose you have some other KO bindings say value, visible then the allBindingAccessor will give you those values and visible binding values also. viewModel he viewmodel object that is bound to the entire page using "ko.applyBindings()". But when your binding is within the with binding or foreach binding then the viewModel parameter will have the $data context instead of the main viewModel. bindingContext The binding context available for the DOM element. This parameter will have all other bindings ($parent, $parents and $root...) as a special property. These init and update callback functions have the same set of parameters. They are element, valueAccessor, allBindingsAccessor, viewModel and bindingContext
  120. 120. Components • Components are a clean and powerful way of organizing your UI code into modular , reusable chunks • Most beneficial for large applications • Simplifies development • Improves runtime performance of your application.
  121. 121. Components Advantages • Represent individual controls and widgets or an entire section • Contain their own view and view model • Be loaded asynchronously • Receive parameters • Nested and inherited • Packaged easily. Registering a component. • ViewModel is optional • Template is required.
  122. 122. Specifying a template • Existing Element ID • Existing Element instance • String of MARKUP • Array of DOM Nodes • Document Fragment • AMD Module
  123. 123. Element Instance
  124. 124. String of MARKUP
  125. 125. Array of DOM Nodes
  126. 126. AMD MODULE (e.g.RequireJS)
  127. 127. ViewModel Key • Can be a function • Can be passed instance to use object directly • Can pass createViewModel to call a function that acts as a factory.
  128. 128. Synchronous/Asynchronous loading • Can be set in registration (synchronous :false) • Default is asynchrnous • Sometimes it has no choice.
  129. 129. Creating Components • Custom Elements: Provide a convenient way of injecting components into views – Convenient syntax for creating components – <like-button>, <date-slider>, <login- form> – Knockout takes care of compatibility (IE6 to IE8 need to register before parsing HTML) – Great way to organize code • Component binding- injects a specific component into an element with optional parameters. • Works extremely similar to custom element and in many cases does the exact same thing
  130. 130. Passing parameters • Interpreted like a JavaScript object literal • You can pass arbitrary values of any type
  131. 131. Component Binding
  132. 132. Component Binding Full API • Name- the name of the component • Params – Object passed to component. Usually a key-value object containing multiple parameters, and usually received by the component’s viewmodel constructor
  133. 133. Component Life Cycle • Component loaders supply vm and template1 • Template is cloned and injected2 • Vm is instantiated3 • Vm is bound to view4 • Component is active5 • Component is torn down and view model is disposed6
  134. 134. 1. Component Loaders supply vm and template • Multiple component loaders may be consulted • Process takes place once per component type • Supplies vm/templates based on what is registered. • Asynchronous process
  135. 135. 2.Template is Cloned • Template is cloned and injected into the container element • Any existing content is removed and discarded
  136. 136. 3. ViewModel is instantiated • If there is a view model- they are not required though • If given a constructor, knockout called new viewModelName(params) • createViewModel is called if given • Always synchronous
  137. 137. 4. ViewModel is bound to view • If no viewmodel, then view is bound to any params supplied to the component binding
  138. 138. 5. Component is active • Component is operating and can be on-screen as long as needed. • If any params are observable, the component can observe changes or write back modified values • Communicates cleanly with parent
  139. 139. 6.Component is torn down • Component is torn down and the viewmodel is disposed • Name values changes observably • Dispose function on the viewmodel is called • If user navigates to new page browsers do automatically • Memory from objects is released.
  140. 140. Template-Only Components • The object to which the view is bound is the params object passed to the component binding
  141. 141. Containerless Components • Passing Params
  142. 142. Passing markup
  143. 143. EMIT JSON DATA • View models are JavaScript Objects, which can be published as a JSON object using JSON serializers like JSON.stringify or json2.js • BUT YOUR VIEW MODELS PROBABLY CONTAIN OBSERVABLES, COMPUTED OBSERVABLES AND OBSERVABLE ARRAYS, which are implemented as Javascript functions and therefore won’t always serialize cleanly. • Ko.toJS -> clones your viewmodel’s object graph, substituting for each observable the current value of that observable, so you get a plain copy that contains only your data and no knockout related artifact. • Ko.toJSON – produces a JSON string representing your view model’s data. Internally, it simply calls to ko.toJS on your view model and then uses the browser’s native JSON serializer on the result.
  144. 144. EMIT JSON DATA
  145. 145. Code Focused Training sak@sycliq.com sak@territorialprescience.com Contact Us Thank You We also provide Code Focused Open House Trainings 153© Syed Awase 2015-16 - KnockOut Ground Up! For code driven trainings Reach out to us +91-9035433124 Current Offerings • AngularJS 1.5.x • TypeScirpt • AngularJS 2 • KnockOutJS • BackBoneJS • Ember JS • Responsive Web Design with Bootstrap, Google Material Design and KendoUI • C# ASP.NET MVC • C# ASP.NET WEB API • C# ASP.NET WCF, WPF • JAVA , SPRING, HIBERNATE • Python , Django • R Statistical Programming INDIA HYDERABAD | BANGALORE | CHENNAI | PUNE OVERSEAS SINGAPORE | MALAYSIA | DUBAI

×