winjs data binding
DESCRIPTION
WinJS Data Binding. Data binding concepts, Bindings in WinJS. George Georgiev. Telerik Software Academy. academy.telerik.com. Technical Trainer. itgeorge.net. Table of Contents. Data Binding Concepts WinJS API for bindings WinJS Binding Basics - PowerPoint PPT PresentationTRANSCRIPT
WinJS Data BindingData binding concepts, Bindings in WinJS
George Georgiev
Telerik Software Academyacademy.telerik.com
Technical Traineritgeorge.net
2
Table of Contents Data Binding
Concepts WinJS API for bindings
WinJS Binding Basics Attributes, observables, binding
data and styles Binding converters Using templates
Data BindingConcepts, Advantages, WinJS APIs
4
Data Binding Data binding connects UI and business logic
The UI layer describes how it visualizes data Properties from sources mapped to
UI elements The Business layer describes the data itself Defines objects and processes
The Data Binding API handles data updates Visualizes data from business logic
in the UI Takes UI data & updates object
properties In good implementations, business
logic has no idea there is UI
Data Binding Advantages to Data Binding
Mechanism to detach UI from business logic
Developer writes less (none) UI interaction code
UI design is independent of development Data sources can be easily mocked
and simulated Disadvantages
A bit slower than direct UI interaction Overhead in detecting data changes
5
Data Binding WinJS supports Data binding
Through WinJS.Binding namespace One-way
Changes to JS objects trigger changes to UI
UI changes DON'T update JS objects Provides attributes to bind UI
controls HTML elements WinJS controls 6
WinJS Binding BasicsElement attributes, bindable objects,
data & style binding
WinJS Binding Basics WinJS bindings use data attributes plus JS code to bind HTML elements data-win-bind – object to element
properties Format:
Example: WinJS.Binding.processAll()
Takes a root element and binding context object
Traverses elements and binds them with context
8
"elementProperty1: objectProperty1; elementProperty2: objectProperty2.subProperty"
<p data-win-bind="innerText: text"></p>
WinJS.Binding.processAll(document.body, {text: 'hi'})
Same as calling with null
WinJS Binding Basics More detail on WinJS.Binding.processAll(): Parses & applies data-win-bind
attributes No data binding occurs if not called
Second parameter defines object context Determines which object is searched
for the properties referenced in data-win-bind
When called with no parameters: Traverses the entire DOM and applies
bindings Only bindings to global objects will
work
9
WinJS Binding Basics Notes on binding
Always have WinJS.Binding.optimizeBindingReferences Prevents memory leaks from binding
Never bind to element IDs Have a collection of your objects
and bind them to the document E.g. a namespace with all objects to
display Access appropriate object for
element through "." operator
10
WinJS Binding BasicsLive Demo
WinJS ObservablesEnabling automatic updates to UI on
object changes
WinJS Observables Binding simple objects doesn't enable updates WinJS needs notification of property
changes Property changes typically handled
in setters Setter gives value then calls an API's
function Mixins in WinJS.Binding enable this
on objects Several methods to convert JS objects to WinJS observables in WinJS.Binding: as() – object to observable define() – object to constructor for
observables Note: work properly ONLY with DTO
s
13
WinJS Observables Using WinJS.Binding.as()
Takes an object to make observable Returns the observable object
Keeps all members and their values All members become observable
properties Methods and properties don't bind properly
Changes to the object are reflected in its binding
14
var personObservable = WinJS.Binding.as({ name: 'Joe', age: 21});WinJS.Binding.processAll(null, personObservable);setInterval(function(){personObservable.age++;}, 1000)
WinJS Observables Using WinJS.Binding.define()
Takes a normal object template and makes a constructor for such observable objects
Returns the object constructor All instances become observable
properties Methods & properties don't bind properly
15
var ObservablePerson = WinJS.Binding.define({ name: "", age: 0});var person = new ObservablePerson();WinJS.Binding.processAll(null, person);person.name = "Joe",person.age = 21;setInterval(function(){personObservable.age++;}, 1000)
WinJS ObservablesLive Demo
Binding ConvertersTranslating object info into UI
appropriate info
Binding Converters Bound property values often need conversion To UI friendly data such as styles,
HTML, etc. To user-friendly texts (3.99 ->
$3,99) Not correct to have UI data in data objects Such as styles, formatting, etc. Remember: data should not be
concerned with how it's displayed Binding APIs usually support some type of Value Converters Compute the representation of a
value
18
Binding Converters WinJS.Binding.converter() function
Receives the function to convert a value Converter passes the function the
value Function should return converted
value Returns the converter function
Called inside a data-win-bind attribute value
19
<div data-win-bind='style.backgroundColor: frequency MyConverters.lightWavelengthToColor'</div>
MyConverters.wavelengthToColor = WinJS.Binding.converters(function(wavelength){ /*return computed CSS color value*/...});
Binding ConvertersLive Demo
Binding TemplatesDefining and reusing formatting for
bindings
Binding Templates Reusable declarative binding elements WinJS.Binding.Template Can contain any piece of HTML Invisible; "instances" are visible
when rendered Can be rendered to the DOM several
times with different bound objects Two ways to initialize templates
Declaratively (needs WinJS.UI.processAll())
JS code, given element or HTML fragment URI
Both ways require some initial HTML code
22
Binding Templates Creating Templates Declaratively
Write the HTML for the template data-win-
control='WinJS.Binding.Template' attribute in the container
Call WinJS.UI.processAll() to parse controls Template container needs to be in
the HTML code of the processed page to be parsed
WinJS will hide the control from the DOM
Access the element through container.winControl
23
Creating Templates Declaratively
Live Demo
Binding Templates Creating Templates in JavaScript
Write the HTML for the template Can be in an external file
Call constructor for WinJS.Binding.Template Pass an HTML element containing the
HTML for the template
Or pass an options object with a href member pointing to a HTML fragment for the template 25
var template = new WinJS.Binding.Template(element)
var template = new WinJS.Binding.Template(null, { href: '/my-templates/sample-template.html})
Creating Templates from Fragments
Live Demo
форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно
програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
курсове и уроци по програмиране, книги – безплатно от Наков
безплатен курс "Качествен програмен код"
алго академия – състезателно програмиране, състезанияASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET
курсове и уроци по програмиране – Телерик академия
курс мобилни приложения с iPhone, Android, WP7, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране
Николай Костов - блог за програмиранеC# курс, програмиране, безплатно
?? ? ?
??? ?
?
? ?
??
?
?
? ?
Questions?
?
WinJS Data Binding
http://academy.telerik.com
Exercises1. Read
this article (and its previous parts) on efficient conversion of objects to WinJS observables
2. Implement a Repeater control. A repeater renders a collection of objects, according to an item template The Repeater is initialized with a
WinJS.Binding.Template Each item the repeater renders uses the
template Items can be wrapped additionally in DIVs
or SPANs The Repeater has a render method, which
takes a collection of objects and a DOM element to which to render them
If the DOM element is not provided, the repeater creates a new DIV and uses it, appending to document
The Repeater should place custom CSS styles to each item it renders, as well as to the container of the items
3. Write an application which enables users to create computer descriptions.
A computer description has all the properties of the computers from demos in this lecture + rating.
Rating is not defined on creation The application should enable
users to save descriptions and should reload all descriptions and visualize them when it starts
Use the repeater from the last Enable rating computers in the
visualized list
29