winjs data binding

29
WinJS Data Binding Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net

Upload: baxter

Post on 23-Feb-2016

75 views

Category:

Documents


0 download

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 Presentation

TRANSCRIPT

Page 1: WinJS  Data Binding

WinJS Data BindingData binding concepts, Bindings in WinJS

George Georgiev

Telerik Software Academyacademy.telerik.com

Technical Traineritgeorge.net

Page 2: WinJS  Data Binding

2

Table of Contents Data Binding

Concepts WinJS API for bindings

WinJS Binding Basics Attributes, observables, binding

data and styles Binding converters Using templates

Page 3: WinJS  Data Binding

Data BindingConcepts, Advantages, WinJS APIs

Page 4: WinJS  Data Binding

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

Page 5: WinJS  Data Binding

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

Page 6: WinJS  Data Binding

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

Page 7: WinJS  Data Binding

WinJS Binding BasicsElement attributes, bindable objects,

data & style binding

Page 8: WinJS  Data 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

Page 9: WinJS  Data Binding

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

Page 10: WinJS  Data Binding

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

Page 11: WinJS  Data Binding

WinJS Binding BasicsLive Demo

Page 12: WinJS  Data Binding

WinJS ObservablesEnabling automatic updates to UI on

object changes

Page 13: WinJS  Data Binding

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

Page 14: WinJS  Data Binding

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)

Page 15: WinJS  Data Binding

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)

Page 16: WinJS  Data Binding

WinJS ObservablesLive Demo

Page 17: WinJS  Data Binding

Binding ConvertersTranslating object info into UI

appropriate info

Page 18: WinJS  Data Binding

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

Page 19: WinJS  Data Binding

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*/...});

Page 20: WinJS  Data Binding

Binding ConvertersLive Demo

Page 21: WinJS  Data Binding

Binding TemplatesDefining and reusing formatting for

bindings

Page 22: WinJS  Data Binding

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

Page 23: WinJS  Data Binding

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

Page 24: WinJS  Data Binding

Creating Templates Declaratively

Live Demo

Page 25: WinJS  Data Binding

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})

Page 26: WinJS  Data Binding

Creating Templates from Fragments

Live Demo

Page 27: WinJS  Data Binding

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен 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

Page 28: WinJS  Data Binding

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

Page 29: WinJS  Data Binding

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