Friday 2 September 2016

Knockout Js Plural Sight



Where can knockout be useful?
Different scenarios where knockout can be very useful.
Separation of concerns in as it appears to HTML5 and JavaScript (separation of structure) Html ,  CSS for  presentation, JavaScript for behavior.
Important because we like to make thinking more maintainable, making it easier to use and kind of follows the SOLID principles or at least the S in SOLID (Single responsibility)

What are the key components of Knockout?
-Dependency Tracking With Observables concept, is a concept similar to the INotifyPropertyChanged interface, which basically means that you're going to have a property, some source object. that when that property gets loaded or changed, its automatically going to notify the UI will reflect that changes and then also you have the option of when that UI might change the value to automatically update the source object again.
-Declarative bindings concept, is the concept of binding your source objects to your elements (target elements) through the HTML itself. So instead of taking JavaScript and saying go find this element by id or by some other means and bind it to this value and this JavaScript OBJECT with my  JSON DATA, instead of doing that through code and then pushing it into the UI and then pulling it out of the UI, we can do that through declarative bindings where inside the HTML element itself, we can say this element is going to get this attribute's property or this value from this source object down in my JavaScript object, and that can work both ways as far as pushing data into the UI and then pulling it back out.
-Templating Support, The third key concept is dealing with templating where you might have repetitive structures in your web page, for example, like rows in a list box or you've just repeated LI's in a numbered list or maybe even rows in a table. So anything you might have that repeats or even just a small view on your screen you can use templates to do this. This is kind of synonymous doing item templates or data templates with XAML technology as well, or if you're more familiar with JavaScript development, you can use things like JQUERY templates as your template engine of choice with Knockout, or you can use the native templates with Knockout, or if some other third-party templating engine.





Valuable Visual Studio Extensions

Web Essentials - Code collapsing, add vendor specific CSS properties, much more
Web Standards Update – HTML intellisense and validation
JSLint – JavaScript Code Analysis
CSSCop – Catches common CSS issues




ko.observable() -  for two way binding.
ko.computed(function(), owner object when using keyword this ie.viewmodel)

Knockout's computed observables don't just work for reading values and calculate them.
They can also calculate them back when somebody writes a value for them. So this is great when somebody wants to allow binding a custom computed observable up into the screen. And it allows me to change it in something like an input in HTML and then write it back to the model.
·         A read function to read the value and to calculate it to display on the screen;
·         a write function for them when somebody changes the value in the screen to parse those values out and store them in one or more observables in your model or view model, then, of course, the owner to specify where the view model is, which is optional.
A great analogy using these is if you've ever. Very similar to XAML converters in this case.
Basically, you're converting from your view model to your screen and then from your screen back to your view model. This is really great for a lot of different situations, which we'll take a look at in the demos in a moment




Code Example
<input data-bind=”value: firstname”/>   // binding a control property to viewmodel property
var myViewModel={
firstname: ko.observable(“John”);   //same as setting a proptery with Inotifychanged
};
ko.applyBindings(myViewModel);   // binds view to a datacontext

MVVM with Knockout (ideal with databinding frameworks)

View (ie Html)


ViewModel ( takes model and represents in a way useful to a view)
- has Behaviours and data for the view
- Contains Properties, Methods, and the model
Model (the data, data could be JSON)



Observable array - ko.observableArray
-          tracks which objects are in array
-          tracks when object is added or removed from array not the individual property state of object.  Use ko.obserable for that.

How to subscribe to a change in an observables

var mysub = viewModel.observableThatChanged.subscribe(function(){ //code here }, viewModel);

To unsubscribe
mysub.dispose();


BUILT IN BINDINGS
Mulitiple bindings possible
i.e data-bind=”enable:allowEditing, value:salesPrice”


“undefined”is null In drop down list;

Bindings

To bind to a property that isn’t specifically created with a built in binding.
use attr.

attr
<a data-bind=”attr: {href:url, titile:modelName}”>



Value Update Actions
Value is generally used for inputs.
The when a value is modified you can update the observable at the various times.



<input type=”text” data-bind=”value:price, valueUpdate:’afterkeydown’”/>
 
How to do a DataBind ForEach example

<div data-bind=”foreach:colors”>
                                                                // parent allows you to jump up out of the loops color data context
<input type=”radio” data-bind=:”value: colorKey, checked: $parent.selectedColorForRadio”/>
<span data-bind=”text:colorText”></span>
<div>

Dom Element Focus Demo
hasFocus – lets you bind what control has focus back to a property in your view Model
data-bind=”hasFocus: thisControlHasFocusProperty”
You can set something to have focus by setting the propery that’s bound to hasFocus to true.
i.e in viewModel
---- thisControlHasFocusProperty(true);

Clicks and other events bindings
Click event example
displayValue: functiuon(){ window.alert(“you click the button”);}
<input type=”text” data-bind=”click:displayValue”>click here</input>

Other event
data-bind=”event: {mouseover: showDetailsSection, mouseout:hideDetailsSection}”              


Css and style Binding
Style example
data-bind=”style:{color: profit() < 0 ? ‘green’ : ‘red'}”
css Exampel
data-bind=”css:{cssClassName: profit() < 0 }”

Two ways of doing jquiry.ready
$(document).ready(handler) ---à $(document).ready(function(){}))
$(handler)   -----------à $(function(){})




JavaScript Patterns
Prevent spaghetti code
use JS namespaces – to prevent your js functions conflicting with another librarys functions

how to create a namespace
var my = my || {}
how to then use that namespace.
my.viewModel =  vm;
my.viewModel = function(){}

object literals
??

Module Pattern. (help create viewmodels in knockout)
Essentially a function you define to create your object;

Areas we’re going to focus on…
Anonymous closures
-- First, anonymous closure is basically taking a function and wrapping inside a parenthesis to become an expression. In here, we've got a function which we can define whatever we want inside it like our view model. All of its public and private members inside to there and all those are scoped inside of that closure. It just helps us contain everything we wanted to and keep that ravioli effect that we've been talking about.
 ( function () {
} ()  ); 

Immediate function invocation
The second piece is immediate function indication. So when you create a module or a function in this case that represents the object module, it's going to be immediately available if you use the immediate function invocation. It basically means, (inaudible) of the end of it. So basically, everything inside of the function is going to be instantiated as soon as it hits that and then it's going to be step two, this instance inside of my doc view model. So we're basically saying, take my doc view model, with other namespace and define that as everything inside this function and run it right away.

( function () {
} ()  );  ß- the extra parenthesise are used for immediate execution

Private public member scopes
The third piece we're looking at is using this same concept but now adding in the concept of the private and public members. So the key thing that the model allows you to do is allow you define different members that you have. And in this case, we've got a val, which is a private value, just with the bad name of course, called private val and it's going to be privately accessible inside of the function not outside.
Anything in the return is public.
var my.viewModel = (function(){
var privateval = 3; <-private
return {
              xProperty:7,                              ß both  public
              add: function(x,y) {};
};
})();

Benefits
·        Modularize code into re-usable objects
·        Variables/functions taken out of global namespace
·        Expose only public members
·        Hide plumbing code
Disadvantages
·         Access public and private members differently


The Revealing Module Pattern
The “revealing module pattern” which adds a few extra things to really make it even better. So with the revealing module pattern, it can only benefits the module pattern plus helps clarify a little bit what-- this is doing for you to this key word. It clears up what's public versus private and helps to reveal private functions with different name. Here, we can see in the example that we've got my view module and at bottom, we're returning out an object literal which is going to contain some val and add. So the only public members that are accessible over my .viewmodel are some val and add that we're going to expose. And then private val in the add function open the private variables are actually just going to be internal variables for this enclosure. So some val specifically refers to private val. What that's doing there as there's some val property is going to be a public property or public method that's exposing and pointing to an internal property or method called private val. So greatly, you can rename methods as well. And in-- as the case of the add function, we can see the add functions using the same name which is just the choice that you have but it's using the name here. This point to an internal function. Now the key to this in using Revealing Module Pattern is that, usually the return statements are very, very short because they're exposing, here is the name of the property or member that I'm going to be exposing. Here's the points to internally instead of having a lot of logic here on the right hand side. Whereas in the in module pattern, you can have a lot of logic under the right hand side. So it's just really a style of coding. Another thing that the Revealing Modern Pattern helps you do is you can help avoid having to refer to the public properties as this dot and then dealing with the private properties that having to do to this. So in the previous example with the module, inside of our code here, we have to refer to a public property saying, "This .mypublicproperty plus private property." So the private properties don't require that to this prefix and the public properties would using the module pattern. Is the revealing module pattern, you don't have to worry that it helps kind of avoid a lot of that since you're moving things up or your logic into your variables, your various statements up here, for your variables, for your properties, for your methods and functions that you have. And then you really chose the return statement to return out and exposure your interface. So with that, let's take a look at how we can apply the Revealing Module Pattern to a Knockout view model and show what advantages it might have.








Templates, Control of Flow and Containerless bindings.

Named Templates
Allows you to reuse a template in multiple locations.
-encapsulate a template for re-use
- template can be created in a script tag, has to be named, and then pointed to using the template data-bind.



Can also be done in a div tag, just give the div a name, and the set display attribute to none so it doesn’t take any space. And then reference it when you want to use it in a data-bind=”template:{name:’’}”      statement




Control of Flow
If and ifnot
The if and ifnot bindings allow you to evaluate a condition to see if it's truthy or falsely and then to execute something based upon that. This can really in handy when you want to execute or only show certain areas of HTML elements and bindings only if a certain conditions exist or if not. So basically if not, it's the opposite of the if.
<td data-bind=”if: product” >     < -render inner tags if there is a product
<td data-bind=”visible: product” >     < -make visible if there is a product

Foreach and with
When using the templates, you can use the foreach to iterate over observable array items. Ie. Could be used for a product list.
Within look the datacontext becomes each line object. To get back up to the view model, you can use $parent or $root.
Data-bind=”template: {name: ‘productsTmpl, foreach:lines}”



Binding Contexts
InlineTemplates
If you’re not reusing a template, there is no need to name a template and put it in a script tag, you can use Control of flow elements to create an implicit template i.e replace this

 with


Dynamically choosing a templay
Containerless bindings