Saturday, August 24, 2013

Control flow in KnockoutJS

foreach binding

duplicates section of markup for each entry in an array. Binds each copy of that markup to array item. You can nest foreach binding with other control-flow bindings such as if and with.

You can use special context property $data, to refer the current array item itself.

You can also use $index to refer the index of current array element. $index is an observable. Similarly you can use $parent to refer to data outside foreach.

Use as option to create alias for the array elements. 

In scenarios like in middle of a list, you can't use foreach binding as above, in such a case you can use containerless control flow syntax which is based on comment tags. 

Note : Destroyed entries are hidden by default. but you can set includeDestroyed option in foreach loop to make them visible. 

if binding

show/hide section of markup based on a condition. This is similar to visible binding.

with binding

Creates a new binding context. Descendent elements are bound in the context of a specified object. with can be used without a container element as well. 

Introduction to KnockoutJS

KnockoutJS is a JavaScript library of MVVM pattern with templates. It does not depend on jQuery. 

With KnockoutJS you can have,

  • Dependency tracking : Automatically update UI when model changes
  • Declarative bindings: Connect parts of your UI to your data model
  • Extensible: Implement custom behaviors

What is MVVM pattern

  • Model : objects and operations in your business domain, this is independent from the UI
  • View Model : Pure code representation of data and operations on a UI. No HTML
  • View: Interactive UI. Representing the state of the ViewModel
Here's a simple example of using KnockoutJS


To achieve two way binding you can use observables. When using observables when you update something in View, changes will be reflected in ViewModel as well.


Explicit subscribing

Used to get notifications when subscribed observable gets changed. You can assign the subscription to a variable and dispose it later.

You can force observables to notify subscribers always by using  
myViewModel.personName.extend({ notify: 'always' });

You can delay change notification by using 
myViewModel.personName.extend({ rateLimit: 50 });

 

Observable Arrays

Just like Observables but for arrays. Observable arrays only track which objects are in the array. Not the state of those objects. Observable array is actually an observable whose value is an array (with some additional methods). Check the documentation for other methods available. For the array also you can delay change notifications like for observables.

 

Computed observables (documentation)

functions that dependent on one or more other observables. Will automatically update when dependencies changes. You can also create writable observables. You can extend this by using rateLimit and notify attributes. 

See complete reference from documentation here


Writable computed observables (documentation

//see the documentation

Pure computed observables (documentation)

This was introduced in 3.2V. Use this if your computed do some calculation and simply returns a value. Here the evaluator does not modify other objects state).

This provides performance and memory benefits. Doesn't maintain subscriptions to its dependencies when it has no subscribers itself.


KnockoutJS - EcmaScript 5 Plugin


http://blog.stevensanderson.com/2013/05/20/knockout-es5-a-plugin-to-simplify-your-syntax/
https://github.com/SteveSanderson/knockout-es5

Friday, August 23, 2013

Using Canvas and SVG in HTML5

Canvas

<canvas> element is used to draw graphics using JavaScript. <canvas> element is only a container to hold the graphics. You must script it to draw the actual graphic.

A canvas is a rectangular area on an HTML page. 

<canvas id="myCanvas" width="200" height="100"

style="border:1px solid #000000;"> </canvas>

Using JavaScript you can manipulate the canvas


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75); 


svg

SVG stands for Scalable vector graphics. They are used to define vector-based graphics for web. SVG defines the graphics in XML format. 

SVG images can be created and edited using any text editor and they can be searched, indexed. SVG images are scalable so it can be printed in high quality at any resolution. 

<svg width="300" height="200">

  <polygon points="100,10 40,198 190,78 10,78 160,198"

  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

You now see that in HTML5 graphics there are 2 ways you can go with either Canvas or SVG. comparison between these 2 will be good in understanding which is better

Monday, August 19, 2013

Bindings in KnockoutJS

Visible binding #

Make associate DOM element hidden or visible. Sets yourElement.style.display as none. 


Text binding #

Display associated text value on DOM. Since the binding sets your text value using a text node, its safe to set any string value without risking HTML or script injection. 


HTML binding #

KO sets element's innerHTML property to your parameter value. Don't use this with untrusted model value due to possible script injection attack. 

CSS Binding #

adds or removes one or more named CSS classes to the associated DOM element. 


Styling Binding #

Directly bind CSS styles


Attr Binding #

provides a generic way to set the values of any attribute for the associated DOM element

Saturday, August 17, 2013

Form field bindings in KnockoutJS

the article is incomplete


click binding



When calling your handler, Knockout will supply the current model value as the first parameter. 

Accessing the event object, passing more parameters
Allowing default click action
Preventing the event from bubbling

event binding



 



Saturday, August 10, 2013

Template binding in KnockoutJS

Template binding populates the associated DOM element with the results of a rendering a template. It’s a good way to build UI structures.

    <div data-bind="template: { name:'person-template', data: buyer }">
    </div>

    <script type="text/html" id="person-template">
        <h3 data-bind="text: name"></h3>
    </script>

    <script type="text/javascript">
        var vm = {
            buyer: {
                name: 'Peter'
            },
            seller: {
                name: 'Jason'
            }
        };

        ko.applyBindings(vm);


    </script>

Native templating: underpins foreach, if, with and other control flow bindings. These will capture the HTML markup contained in your element and use it as a template to render against arbitrary data item. This is built into KO.

String based templating: way to connect KO to 3rd party templating engines. KO will pass your model values to external template engine and inject the resulting markup string into document.

Notes:
Avoid combining other bindings with template binding, especially under data-heavy scenarios. Knockout uses one computed observable to track all bindings of an element.

See Ryan's article here

Parameters
Main parameter: Shorthand syntax: if you just supply a string value, KO will interpret this as the ID of a template to render.


For more control, pass a JavaScript object with some combination of the following properties

Rendering a named template
Normally when using control flow bindings, there’s no need to give names to your template. But if you want you can factor out template in to separate element and reference them by name.

Resources
http://www.strathweb.com/2012/08/knockout-js-pro-tips-working-with-templates/
http://aboutcode.net/2012/11/15/twitter-bootstrap-modals-and-knockoutjs.html

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook