Top Banner
IntelliMeet April, 14 KnockoutJS and MVVM Manvendra SK Twitter: @Manvendra_SK
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
  • IntelliMeet April, 14 KnockoutJS and MVVM Manvendra SKTwitter: @Manvendra_SK

  • What Is KnockoutJS ?Rich client-side interactivityMVVM patternWeb browser support

  • What Is The Problem ?What Is The Solution ?

  • What KnockoutJS Is Not ?Client side codeServer codeDatabaseKnockoutJS

  • What Is MVVM ?ViewViewModelModel

  • Core Observable TypesComputedObservable ArrayObservable

  • How Knockouts Observables Works ?Changes to Targets Notify SourceTwo-Way Data BindingChanges to Source Notify TargetsEvent Binding

  • Observable And BindingMake Property on object an observable using ko.observable() method passing default value.

    Call ko.applyBindings() method passing object to method.

    Bind properties of ViewModel object to html elements using data-bind attribute any binding like text. More on this later.

    You can make the object using a constructor. *

  • Observable TricksAny property that is declared observable is a function like getter and setter.

    To access property use:

    To set property use:

    Dont ever use = operator to assign values. Youll overwrite the observable.

  • Interactive BindingWe have used text binding. That was a non-interactive binding.

    Interactive binding is when user interact with the page and hence the binding.

    click is such a binding.

    More on this later.

  • Computed ObservableDefine Your Own Derived PropertyBased On Other Properties and ObservablesWhen You Need A Value That Doesnt Exist in Web ServiceAlso Supports Data Binding

  • Computed Observable And BindingMake Property on object an computed observable using ko.computed() method passing a anonymous function that returns computed value.

    Bind to html elements using data-bind attribute.

  • Observable ArrayNotify When Items Are Added Or RemovedNo Notification When Objects In The Array ChangeTracks Which Objects Are In The ArrayBonus: Can Use Array Functions

  • Observable Array And BindingMake Property on object an observable array using ko.observableArray() method passing an array literal.

    Bind to html elements using data-bind attribute and foreach binding.

    Binding contexts inside foreach: $root et al. More on this later.

    mvObject.arrayProp() gives you native underlying array.

  • Observable Array Methodspush(), pop()

    unshift(), shift(), slice()

    remove(), removeAll(), destroy(), destroyAll()

    sort(), reversed()


  • Built In BindingsBinding For Element AttributesMultiple Binding ExpressionsBuilt Into Knockout

  • Control Flow BindingsforeachififnottexthtmlvisiblecssstyleattrclickvalueeventenabledisablecheckedoptionsselectedOptionshasfocuswith

  • Appearance BindingsforeachififnottexthtmlvisiblecssstyleattrclickvalueeventenabledisablecheckedoptionsselectedOptionshasfocuswith

  • Interactive BindingsforeachififnottexthtmlvisiblecssstyleattrclickvalueeventenabledisablecheckedoptionsselectedOptionshasfocuswith

  • Control Flow Bindings

  • foreach Binding

  • Binding ContextsWhat if you need to access ViewModel object while iterating array using foreach binding?

    $root : Top level ViewModel object.

    $data : Refers to object for the current context. Like this keyword in JavaScript. Useful for atomic values like strings and numbers.

    $index : Obviously index number of current item.

  • Binding Contexts$parent : Refers to the parent ViewModel object. Typically used inside nested loops and when you need to access properties in the outer loop.

  • if And ifnot Bindings

  • with BindingUsed when you want to manually declare block scope to particular property of ViewModel.

  • Appearance Bindings

  • text Bindinghtml Bindingvisible Bindingattr Binding

  • style Bindingcss Binding

  • Interactive Bindings

  • click Bindingclick binding is one of the simplest interactive binding. It just calls a method on your ViewModel when the user click the element passing function two arguments model and event.

    vmObject.someMethod = function(model, event) {// do what ever you want here };

  • value BindingSimilar to text binding. But this time user can update the value from the View and ViewModel will update accordingly. Thus value binding is two way binding.

  • event BindingThe event binding lets you listen for arbitrary DOM events on any HTML element.

    As it can listen for multiple events, it requires an object to map events. Just like attr binding.

    data-bind=event: {mouseover: someMethod, mouseOut: someOtherMethod}

  • event BindingThe function will take two arguments called data and event.

    vmObject.someMethod = function(data, event) {// do what ever you want on happening// of this event };

  • A Better event Binding

  • enable and disable BindingUsed to enable or disable some form element on some particular condition.

  • checked BindingUsed to select or deselect HTMLs selectable elements like check boxes and radio buttons.

    We can also use arrays instead of true or false value in the observable. In this case only those check boxes will be selected whose value attribute value exist in the array.

    Matches value attribute value of radio button to single value in observable.

  • options BindingThis binding is used to build options elements inside a select element from an observable array.

    value binding is used to preselect or get the selected item in the select list.

    optionsText binding is used to show the content on the view when using objects in the observable array instead of literals.

  • selectedOptions BindingAs a select list can be made to select multiple items so to retrieve or set all the selected items we need an array instead of using an atomic value. Thus instead of value binding we use selectedOptions binding.

  • hasfocus BindingAllows us to put the focus on any element.

  • Interacting With ServerSaving DataMapping Data To ViewModelLoading Data

  • Mapping Data To ViewModelMapping plugin dynamically generates new observables.

  • Animation Inside KnockoutDont support animation from core, as its a view binding library not DOM manipulation library.

    All Knockouts automatic updates are immediately applied whenever underlying data changes.

  • List CallbacksKnockout is a powerful user interface library on its own, but once you combine it with the animation capabilities of a framework like jQuery or MooTools, youre ready to create truly stunning UIs with minimal markup.

    The foreach binding has two callbacks named beforeRemove and afterAdd. These functions are executed before an item is removed from the list or after its been added to the list, respectively. This is our chance to put in animation logic before Knockout manipulates the DOM.

  • List CallbacksThese callbacks take a parameter named element which a reference to the element which Knockout is manipulating.

  • Custom BindingsOkey, were having fun with foreach binding and its some level support for plugging in animation logic. But what about other bindings? They dont support this already. So Custom Bindings is answer to the question.

    We can make our own bindings by adding an object defining the binding to ko.bindingHandlers. This also happens to be where all of the built-in bindings are defined, too.

  • Custom BindingsThe object should have two methods namely init and update.

    init method is called when Knockout first encounters the binding. So this callback should define the initial state for the view component and perform necessary setup actions like registering event listeners.

  • Custom BindingsThe update method executes whenever the associated observable changes.

    Both methods take same two parameters namely element and valueAccessor.

    The element parameter is the DOM element being bound, and valueAccessor is a function that will return the ViewModel property in question (here it is binding value).

  • ConclusionKnockout.js is a pure JavaScript library that makes it incredibly easy to build dynamic, data-centric user interfaces.

    We covered most of the Knockout.js API, but there are still a number of nuances left to discover.

    Knockout.js provides plethora of extensibility opportunities for you to explore!

  • Questions ?

  • Thanks...