SlideShare uma empresa Scribd logo
1 de 43
DataBindingcom
Microsoft WebCamp 2014
20 de Maio de 2014
2Sobremim
/43
João Pedro “jota” Martins
CTO
jota@create.pt
@lokijota
http://blogit.create.pt/blogs/joaomartins
http://www.linkedin.com/in/joaopedromartins
3Agenda
 O que é KnockoutJS?
 Observables
 Computed Members
 ObservableArrays
 Bindings nativos
 Templatese controlode fluxo
 Extensãode Binding Handlers
 Temas relâmpago:
 MappingPlugin,Extenders,KoUtils,Debug/troubleshooting
/43
4OqueéKnockoutJS?
 BibliotecaJavascriptque ajuda na criaçãode interfacesdinâmicos
sobreum modelo de dados limpo, usando MVVM.
 Poroutraspalavras:éuma frameworkJavascriptde data binding para
aplicaçõesWeb.
ELEVATORPITCH /43
5Apresentaçãorápida
 Grátise opensource,criadoem2010por SteveSanderson
 Javascriptpuro– funcionacomoutrasframeworks, serverou client-side
 Compacto-47kb‘minificado’(~13kbusandogzip)
 Semdependências(jQueryopcional,p.ex.)
 Suporta[praticamente]todososbrowsers
 IE6+(!!),Firefox2+,Chrome,Opera,Safari(desktop/mobile)
 Completamentedocumentadoe comcomunidadeactiva
 DocumentaçãodaAPI,exemplosfuncionais,tutoriaisinteractivos,blogs,Google
Group
 Versãoactual:3.1.0egrandefocoem retro-compatibilidade
OQUEÉKNOCKOUTJS? /43
6+ 2+
6Funcionalidades
 Bindings declarativos
 Associaçãode elementosdo DOMaum modeloemJavascriptcomuma
sintaxeconciseelegível
 Actualizaçãoautomática do InterfaceUtilizadore Modelo
 Sempreque omodelomuda,o IUéactualizado(evice-versa)
 Gestão de dependências
 Identificaçãoimplícitadedependênciasentrecamposdo modelo
 Templating
 Geraçãodeinterfacescombasenos dadosdo modelo
OQUEÉKNOCKOUTJS? /43
MVVM
/43
7
OQUEÉKNOCKOUTJS?
MODEL
Server/DB Javascript+Observables HTML + Bindings
VIEWVIEW MODEL AUTO
UserInterfaceem
HTML
Backenddelógica
edados,podeser
qualquer
tecnologia
ModeloOOdo
UserInterface,
comdadose
lógicadaUI
Dadose
acções
JavascriptBrothersinArms
jQuery
Substitutocross-browserpara
umaAPIinconsistentedoDOM
Mecanismobaixonívelde
manipularelementoseevent
handlersempáginasWeb
/43
8
AngularJS
Frameworkcompletaalto-nível
paradesenvolvimentodeSingle
PageApplications(SPA)
ComparávelaDurandal
KnockoutJS
Frameworkalto-nívelpara
mapeamentoentremodelosde
dadoseinterfacesWeb,usando
padrãoMVVM
KOJSusajQueryseestiver
disponível
OQUENÃOÉKNOCKOUTJS?
KnockoutJSem3passos
<input data-bind="value:firstName"/>
OQUEÉKNOCKOUTJS?
Binding
declarativo
ko.observable
ko.applyBindings
Criar
observable
Ligar (bind) do
ViewModel à View
/43
9
KOJS101
DEMO01
Sagan
Carl SaganCarl Sagan
Sagan
Observables
 Encapsularpropriedadescoma função“observable”
 ko.observable() ou ko.observable(valor_inicial);
 Binding bi-direccional
 TantoUIcomomodelosãoactualizados
CONCEITOSBASE /43
11
Bindingbi-direccional
CONCEITOSBASE
data-bind
Binding
declarativo
product: {
id: 1001,
model: ko.observable(“Surface 2 Pro"),
salePrice: ko.observable(1199.95)
}
ko.applyBindings(product);
Objecto de dados
Ligar UI a dados e vice-versa (wireup)
/43
12
Observables
DEMO02
Membroscalculados-Computed
 Definiruma função que defineum valor,e usarisso no binding
 Ex:Nomecompleto,PhotoUrl,Montantestotais
 Quando os observablessão alterados,os camposcomputedtambém
são notificados– detecçãoimplícita de dependências
 Gestão de “this”…
 Pode sernecessáriopassarinformaçãosobreo“this”paraocomputed
CONCEITOSBASE /43
14
DefinirumapropriedadeComputed
vm= {
id:ko.observable(1),
unitPrice:ko.observable(4199),
:ko.observable(2)
};
vm.extendedPrice= ko.computed(function(){
returnthis.product()?
this.unitPrice()* parseInt("0"+ this.qty(),10):0;
},vm);
CONCEITOSBASE
observables
Owner (=this)
/43
15
ComputedObservables
DEMO03
ObservableArray
 Permite‘seguir’os itens de um array,não o seu estadointerno
 Notificaçõesgeradasquando itens são Adicionadosou Removidosdo
Array
 Suporta API normais sobrearrays(push, pop, length,…)
 Não são geradasnotificaçõesquando as propriedadesde itensdo
arraysão alterados
 Necessáriousarko.observable()nessaspropriedadestambém
CONCEITOSBASE /43
17
ExemplodeObservableArray
CONCEITOSBASE
var myViewModel = {
salesPerson: ko.observable(“Luis Calado"),
empNum: ko.observable(666),
products: ko.observableArray([
{ model: “Surface Pro", price: 1749, id=123 },
{ model: “Windows Azure", price: 189, id=456 }
])
};
<span data-bind="text: products().length"></span>
Pré-popular com
dados
Agir sobre o
observable array
/43
18
ObservableArray
DEMO04
Bindings
<input type="text"
data-bind="enable:allowEditing, value:salePrice"/>
<selectdata-bind="options:colors,
value:selectedColor,
optionsText:'name',
optionsValue:'key'" ></select>
CONCEITOSBASE
Nativos de
Knockout
Binding a atributos
de elementos
Vários bindings
num elemento
/43
20
Bindingsnativos(2)
CONCEITOSBASE
attr checked click css disable
enable event hasfocus html options
optionsText optionsValue selectedOptions style submit
text uniqueName value visibletext value
click disable
enable
attr
Display and state bindings
Text and value bindingsBindings for specific attributes
visible
event
Event bindings
/43
21
Bindingsnativos
DEMO05
Templates:controldefluxo
CONCEITOSBÁSICOS
• Se condição “truthy”if
• Se condição “falsy”ifnot
• Executar para cada item numa listaforeach
• Especificar sub-scope do viewModelwith
/43
23
24Templates–inlinetemplates
<tbody data-bind="foreach:lines">
<tr>
<td style="width: 100px;">
<input data-bind="value:quantity" />
</td>
...
</tr>
</tbody>
CONCEITOSBÁSICOS /43
Templates–namedtemplates
<tbodydata-bind="template:{name:'productsTmpl',foreach:lines}">
</tbody>
<scripttype="text/html"id="productsTmpl">
<tr>
<tdstyle="width:100px;">
<inputdata-bind="value:quantity"/>
</td>
...
</tr>
</script>
CONCEITOSBÁSICOS
Passar o contexto para a template com o “foreach”
/43
25
Condições
<p data-bind="if:lines().length> 0">
<span>Total value:</span>
<span data-bind="text:grandTotal()"></span>
</p>
CONCEITOSBÁSICOS
Qualquer expressão
“truthy”
/43
26
Especificarocontexto
<divdata-bind="with:model">
<divdata-bind="text: brand"></div>
<divdata-bind="text: name"></div>
</div>
<div>
<div data-bind="text: model().brand"></div>
<div data-bind="text: model().name"></div>
</div>
CONCEITOSBÁSICOS
Controlodefluxoetemplates(foreach)
DEMO06
ControlodefluxosemcontainerHTML
 UtilizaçãodecomentáriosHTML
 Comentáriousaelementosdecontroldefluxo
 if
 ifnot
 foreach
 with
 Template
<!--koforeach:myItems-->
…
<!--/ko-->
CONCEITOSBÁSICOS /43
29
Parte do motor
de templating nativo
do KnockoutJS
Controlodefluxosemcontainer
DEMO07
OquesãoCustomBindingHandlers?
 Mecanismodeextensibilidadedebindings
 Exemplos
 Arredondareapresentarcomovalormonetário
 Animarumatransição
 fadeVisible
 IntegrarcomjQueryUI
 jqButton
 Ratingscomestrelas
 starRating
 Fazerlogging
CONCEITOSBASE /43
31
ComocriarumBindingHandler
ko.bindingHandlers.fadeVisible={
:function(element,valueAccessor){
//...
},
:function(element,valueAccessor){
//...
}
}
CONCEITOSBASE
Executado na primeira
avaliação do binding
Executado depois do init,
cada vez que um dos
observables mude
/43
32
BindingHandler-parâmetros
ko.bindingHandlers.fadeVisible= {
init:function(element,valueAccessor,allBindingsAccessor,viewModel){
varshouldDisplay= valueAccessor();
$(element).toggle(shouldDisplay);
},
update:function(element,valueAccessor,allBindingsAccessor,viewModel){
varshouldDisplay= valueAccessor();
shouldDisplay?$(element).fadeIn():$(element).fadeOut();
}
}
Elemento do
DOM
Parâmetro
binding
Outros bindings
do elemento
viewmodel
CustomBindingHandlers
DEMO08
Mapping
 Mapping Plugin
 ExtensãoaoKnockout(downloadoficialseparado)
 Converteum objectoJSparaum objectoobservável,recursivamente
 Possibilidadedeparametrizaroperação
 ko.mapping.fromJS(jsdata)eko.mapping.toJS(viewModel);
 Podeterproblemasde desempenho.Alternativa:
 KnockoutWrap
OUTROSTEMAS /43
35
36Extenders
 Permitemadicionar funcionalidadeextraaos nossosobservablesque
filtram a forma comonotificaçõessão geradas
 Ex. de nativos:
 myViewModel.personName.extend({rateLimit:50 });// limitataxadeeventos
 myViewModel.personName.extend({notify:'always'});// forçasync
 Ex. de desenvolvidosà medida:
 this.firstName=ko.observable(“jota").extend({logChange:"firstname"});
OUTROSTEMAS /43
37KOUtils
 Despistardadosusadosparafazerbindcomumelemento:
 ko.dataFor(element)–dadoscomqueoelementfoi‘binded’
 ko.contextFor(element)–todoo‘bindingcontext’disponívelparaoelementDOM
 ko.toJS–criacópiadeumviewModelremovendotodaaestruturadoKO
 ko.toJSON–chamatoJSedepoisconverteoresultadoparaJSON
 JSON.stringify(viewModel)ignorafunções,eobservablessãofunções…
 ko.utils.parseJSON(str)–semelhanteaJSON.parse.Aseguirimplicausarmappingplugin
 ko.utils.arrayMap(str,delegate)–iteranumarrayeaplicaumdelegate(semelhantealambda),
devolvendocolecção
varmappedData=ko.utils.arrayMap(jsonData,function(item){
returnnewItem(item.name,item.category,item.price);
});
 ko.utils.arrayForEach(val,delegate)–iteranumarrayeaplicaumdelegate
 ko.utils.arrayFilter(val,boolDelegate)–filtraarray
OUTROSTEMAS /43
38DebugeTroubleshooting
<predata-bind=“text:ko.toJSON($data,0, 2)”></pre>
<inputdata-bind=“uniqueIName:console.log($data),value:description/>
 KnockoutContextDebugger(chromeextension)edev-consoledobrowser
 Performance–quantasvezesdisparaumbinding?Apenasdeveser
observableo quedeverterfluxobi-direccional
OUTROSTEMAS /43
Justonemoredemo
DEMO09
40Resumindo–KnockoutJSéumabiblioteca…
Específica e pequena
Compatível com vários browsers e outras
frameworks
Permite sincronização automática da alterações e
suporta melhor estruturação de código Javascript
/43
41Horasdediversão
DocumentaçãoeDownload
 Homepageedocumentação:http://knockoutjs.com
 BlogSteveSanderson:http://blog.stevensanderson.com
 BlogRyanNiemeyer:http://knockmeout.net
 Código:https://github.com/knockout/knockout/releases
Extraseextensões
 KnockoutValidation:https://github.com/Knockout-Contrib/Knockout-Validation
 KnockoutWrap:https://github.com/arj03/knockout.wrap
 Knockout-es5:https://github.com/SteveSanderson/knockout-es5
 KnockoutDelegatedEvents:https://github.com/rniemeyer/knockout-delegatedEvents
 GoogleChromeExtension:Knockoutjscontextdebugger
Comunidade
 https://groups.google.com/forum/#!forum/knockoutjs
 http://stackoverflow.com “knockoutjs”
/43
Obrigado!
jota@create.pt
@lokijota
http://blogit.create.pt/blogs/joaomartins
http://www.linkedin.com/in/joaopedromartins
20140520 Microsoft WebCamp - DataBinding with KnockoutJS

Mais conteúdo relacionado

Semelhante a 20140520 Microsoft WebCamp - DataBinding with KnockoutJS

Seu Cliente no Controle! Testes ágeis
Seu Cliente no Controle! Testes ágeisSeu Cliente no Controle! Testes ágeis
Seu Cliente no Controle! Testes ágeisVanderson Silva
 
LambdaDay: Backbone.js
LambdaDay: Backbone.jsLambdaDay: Backbone.js
LambdaDay: Backbone.jsGiovanni Bassi
 
Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009
Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009
Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009Ramon Durães
 
Geração de Código com o MyGeneration
Geração de Código com o MyGenerationGeração de Código com o MyGeneration
Geração de Código com o MyGenerationComunidade NetPonto
 
Ferramenta Flow - Análise estática de códigos javascript
Ferramenta Flow - Análise estática de códigos javascriptFerramenta Flow - Análise estática de códigos javascript
Ferramenta Flow - Análise estática de códigos javascriptRodrigo Ferreira
 
Backbone.js nas trincheiras
Backbone.js nas trincheirasBackbone.js nas trincheiras
Backbone.js nas trincheirasLambda 3
 
jQuery e ASP.Net MVC a dupla dinâmica
jQuery e ASP.Net MVC a dupla dinâmicajQuery e ASP.Net MVC a dupla dinâmica
jQuery e ASP.Net MVC a dupla dinâmicaVictor Cavalcante
 
Treinamento ASP.NET 2014
Treinamento ASP.NET 2014Treinamento ASP.NET 2014
Treinamento ASP.NET 2014Eric Gallardo
 
IoTizando com JavaScript
IoTizando com JavaScriptIoTizando com JavaScript
IoTizando com JavaScriptHeider Lopes
 
Demoiselle Behave - Parte 1
Demoiselle Behave - Parte 1Demoiselle Behave - Parte 1
Demoiselle Behave - Parte 1Vanderson Silva
 
Workshop Node.js + MongoDB + Mongoose
Workshop Node.js + MongoDB + MongooseWorkshop Node.js + MongoDB + Mongoose
Workshop Node.js + MongoDB + MongooseLuiz Duarte
 
Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010
Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010
Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010Rodrigo Kono
 
JSF 2.0 e ScrumToys
JSF 2.0 e ScrumToysJSF 2.0 e ScrumToys
JSF 2.0 e ScrumToysDr. Spock
 

Semelhante a 20140520 Microsoft WebCamp - DataBinding with KnockoutJS (20)

Arquitetura de sistemas web
Arquitetura de sistemas webArquitetura de sistemas web
Arquitetura de sistemas web
 
Seu Cliente no Controle! Testes ágeis
Seu Cliente no Controle! Testes ágeisSeu Cliente no Controle! Testes ágeis
Seu Cliente no Controle! Testes ágeis
 
LambdaDay: Backbone.js
LambdaDay: Backbone.jsLambdaDay: Backbone.js
LambdaDay: Backbone.js
 
JavaServer Faces
JavaServer FacesJavaServer Faces
JavaServer Faces
 
Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009
Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009
Introdução ao ASP.NET 3.5 - Campus Party Brasil 2009
 
Hello vue
Hello vueHello vue
Hello vue
 
Windows Server 2008: Gerenciamento
Windows Server 2008: GerenciamentoWindows Server 2008: Gerenciamento
Windows Server 2008: Gerenciamento
 
Geração de Código com o MyGeneration
Geração de Código com o MyGenerationGeração de Código com o MyGeneration
Geração de Código com o MyGeneration
 
Ferramenta Flow - Análise estática de códigos javascript
Ferramenta Flow - Análise estática de códigos javascriptFerramenta Flow - Análise estática de códigos javascript
Ferramenta Flow - Análise estática de códigos javascript
 
Backbone.js nas trincheiras
Backbone.js nas trincheirasBackbone.js nas trincheiras
Backbone.js nas trincheiras
 
.NET Micro Framework
.NET Micro Framework.NET Micro Framework
.NET Micro Framework
 
MongoDB + PHP
MongoDB + PHPMongoDB + PHP
MongoDB + PHP
 
jQuery e ASP.Net MVC a dupla dinâmica
jQuery e ASP.Net MVC a dupla dinâmicajQuery e ASP.Net MVC a dupla dinâmica
jQuery e ASP.Net MVC a dupla dinâmica
 
Treinamento ASP.NET 2014
Treinamento ASP.NET 2014Treinamento ASP.NET 2014
Treinamento ASP.NET 2014
 
IoTizando com JavaScript
IoTizando com JavaScriptIoTizando com JavaScript
IoTizando com JavaScript
 
Demoiselle Behave - Parte 1
Demoiselle Behave - Parte 1Demoiselle Behave - Parte 1
Demoiselle Behave - Parte 1
 
MS Enterprise Library
MS Enterprise LibraryMS Enterprise Library
MS Enterprise Library
 
Workshop Node.js + MongoDB + Mongoose
Workshop Node.js + MongoDB + MongooseWorkshop Node.js + MongoDB + Mongoose
Workshop Node.js + MongoDB + Mongoose
 
Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010
Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010
Faça Sucesso Desenvolvendo com ASP.NET 4, ASP NET MVC e Visual Studio 2010
 
JSF 2.0 e ScrumToys
JSF 2.0 e ScrumToysJSF 2.0 e ScrumToys
JSF 2.0 e ScrumToys
 

Mais de João Pedro Martins

Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?João Pedro Martins
 
The new Azure App Service Architecture
The new Azure App Service ArchitectureThe new Azure App Service Architecture
The new Azure App Service ArchitectureJoão Pedro Martins
 
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedJoão Pedro Martins
 
Architecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedArchitecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedJoão Pedro Martins
 
Power your website with Windows Azure
Power your website with Windows AzurePower your website with Windows Azure
Power your website with Windows AzureJoão Pedro Martins
 
Software Estimation - A Step Closer to the Silver Bullet
Software Estimation - A Step Closer to the Silver BulletSoftware Estimation - A Step Closer to the Silver Bullet
Software Estimation - A Step Closer to the Silver BulletJoão Pedro Martins
 
eCommerce Solutions on Windows Azure
eCommerce Solutions on Windows AzureeCommerce Solutions on Windows Azure
eCommerce Solutions on Windows AzureJoão Pedro Martins
 

Mais de João Pedro Martins (8)

Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
Azure Service Fabric and the Actor Model: when did we forget Object Orientation?
 
Azure Service Fabric Overview
Azure Service Fabric OverviewAzure Service Fabric Overview
Azure Service Fabric Overview
 
The new Azure App Service Architecture
The new Azure App Service ArchitectureThe new Azure App Service Architecture
The new Azure App Service Architecture
 
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons LearnedITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
ITARC15 Workshop - Architecting a Large Software Project - Lessons Learned
 
Architecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons LearnedArchitecting a Large Software Project - Lessons Learned
Architecting a Large Software Project - Lessons Learned
 
Power your website with Windows Azure
Power your website with Windows AzurePower your website with Windows Azure
Power your website with Windows Azure
 
Software Estimation - A Step Closer to the Silver Bullet
Software Estimation - A Step Closer to the Silver BulletSoftware Estimation - A Step Closer to the Silver Bullet
Software Estimation - A Step Closer to the Silver Bullet
 
eCommerce Solutions on Windows Azure
eCommerce Solutions on Windows AzureeCommerce Solutions on Windows Azure
eCommerce Solutions on Windows Azure
 

20140520 Microsoft WebCamp - DataBinding with KnockoutJS

Notas do Editor

  1. Knockout is a JavaScript library that helps us to create rich, responsive and dynamic display with a clean underlying data model.
  2. MIT license
  3. Ok já vimos como ter observação, mas como é que ligamos as coisas quando temos mais que texto e values?
  4. http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html
  5. Fazer demo com o exemplo do Google Fazer algum exemplo mais complexo: shopping cart, email cliente, alguma coisa com json a ser lido/escrito do servidor? Todo?
  6. Description Shows the knockout context & data for the selected dom node in a sidebar of the elements pane. Knockoutjs debugging extension. Adds a extra sidebar in the elements pane of the chrome dev tools with the relevant knockout context and data for the selected element. Very usefull if you got large/nested viewmodels. Allows to add tracing to every observable/computed. Allows to edit observables from the console.(https://github.com/timstuyckens/chromeextensions-knockoutjs/wiki/Editing-viewmodel-binding-values) Source code is on github: https://github.com/timstuyckens/chromeextensions-knockoutjs