SlideShare a Scribd company logo
1 of 6
Knockout Extender

Bryan Lin
2013/11/01
Using extenders to augment
observables
Knockout observables provide the basic features necessary to support
reading/writing values and notifying subscribers when that value changes
Using extenders to augment
observables
How to create an extender
Using the ko.extenders object
ko.extenders.logChange = function(target, option) {
target.subscribe(function(newValue) {
console.log(option + ": " + newValue);
});
return target;
};
this.firstName = ko.observable("Bob").extend({logChange: "first name"});
Using extenders to augment
observables
How to create an extender
 View:
<p><input data-bind="value: myNumberOne" /> (round to whole number)</p>
<p><input data-bind="value: myNumberTwo" /> (round to two decimals)</p>
ko.extenders.numeric = function(target, precision) {
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a
notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;

};
function AppViewModel(one, two) {
this.myNumberOne = ko.observable(one).extend({ numeric: 0 });
this.myNumberTwo = ko.observable(two).extend({ numeric: 2 });
}
ko.applyBindings(new AppViewModel(221.2234, 123.4525));
References
http://knockoutjs.com/
http://jsbin.com/ahelar/49/edit

More Related Content

What's hot

AWS Fargate in practice. How to run containers without managing EC2 instances
AWS Fargate in practice. How to run containers without managing EC2 instancesAWS Fargate in practice. How to run containers without managing EC2 instances
AWS Fargate in practice. How to run containers without managing EC2 instances
Max Borysov
 
Hight Work
Hight WorkHight Work
Hight Work
Nutron
 
Our challenge for Bulkload reliability improvement
Our challenge for Bulkload reliability  improvementOur challenge for Bulkload reliability  improvement
Our challenge for Bulkload reliability improvement
Satoshi Akama
 

What's hot (20)

Functional Programming In JS
Functional Programming In JSFunctional Programming In JS
Functional Programming In JS
 
CITYSEARCH
CITYSEARCHCITYSEARCH
CITYSEARCH
 
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
Performance Optimization 101 for Ruby developers - Nihad Abbasov (ENG) | Ruby...
 
Google Cloud Dataflow meets TensorFlow
Google Cloud Dataflow meets TensorFlowGoogle Cloud Dataflow meets TensorFlow
Google Cloud Dataflow meets TensorFlow
 
Hybrid Application Development for Maemo N900 Device using Qt Webkit - Discov...
Hybrid Application Development for Maemo N900 Device using Qt Webkit - Discov...Hybrid Application Development for Maemo N900 Device using Qt Webkit - Discov...
Hybrid Application Development for Maemo N900 Device using Qt Webkit - Discov...
 
SignalR: Above & Beyond Chat
SignalR: Above & Beyond ChatSignalR: Above & Beyond Chat
SignalR: Above & Beyond Chat
 
ButterKnife
ButterKnifeButterKnife
ButterKnife
 
AWS Fargate in practice. How to run containers without managing EC2 instances
AWS Fargate in practice. How to run containers without managing EC2 instancesAWS Fargate in practice. How to run containers without managing EC2 instances
AWS Fargate in practice. How to run containers without managing EC2 instances
 
Weightlifting at SimplySocial
Weightlifting at SimplySocialWeightlifting at SimplySocial
Weightlifting at SimplySocial
 
05 binding and action
05 binding and action05 binding and action
05 binding and action
 
Lettuce example using scenarios outline
Lettuce example using scenarios outlineLettuce example using scenarios outline
Lettuce example using scenarios outline
 
Sbt for mere mortals
Sbt for mere mortalsSbt for mere mortals
Sbt for mere mortals
 
Function
FunctionFunction
Function
 
Use of django at jolt online v3
Use of django at jolt online v3Use of django at jolt online v3
Use of django at jolt online v3
 
Hight Work
Hight WorkHight Work
Hight Work
 
Ansible party in the [Google] clouds
Ansible party in the [Google] cloudsAnsible party in the [Google] clouds
Ansible party in the [Google] clouds
 
Session 2 android study jam
Session 2 android study jamSession 2 android study jam
Session 2 android study jam
 
PSGI REST API
PSGI REST APIPSGI REST API
PSGI REST API
 
Our challenge for Bulkload reliability improvement
Our challenge for Bulkload reliability  improvementOur challenge for Bulkload reliability  improvement
Our challenge for Bulkload reliability improvement
 
Elasticsearch @ Keboola
Elasticsearch @ KeboolaElasticsearch @ Keboola
Elasticsearch @ Keboola
 

Viewers also liked

Bootstrap - component
Bootstrap - componentBootstrap - component
Bootstrap - component
LearningTech
 
Power shell – object 篇
Power shell – object 篇Power shell – object 篇
Power shell – object 篇
LearningTech
 
Self-Hosta Web API
Self-Hosta Web APISelf-Hosta Web API
Self-Hosta Web API
LearningTech
 
Asp.net controller
Asp.net controllerAsp.net controller
Asp.net controller
LearningTech
 
Vs 2012 publishing profiles and copy files using ms builld commands
Vs 2012 publishing profiles and copy files using ms builld commandsVs 2012 publishing profiles and copy files using ms builld commands
Vs 2012 publishing profiles and copy files using ms builld commands
LearningTech
 
Css 選擇器規劃
Css 選擇器規劃Css 選擇器規劃
Css 選擇器規劃
LearningTech
 

Viewers also liked (8)

Bootstrap - component
Bootstrap - componentBootstrap - component
Bootstrap - component
 
Power shell – object 篇
Power shell – object 篇Power shell – object 篇
Power shell – object 篇
 
Self-Hosta Web API
Self-Hosta Web APISelf-Hosta Web API
Self-Hosta Web API
 
Sse
SseSse
Sse
 
Asp.net controller
Asp.net controllerAsp.net controller
Asp.net controller
 
Tuple
TupleTuple
Tuple
 
Vs 2012 publishing profiles and copy files using ms builld commands
Vs 2012 publishing profiles and copy files using ms builld commandsVs 2012 publishing profiles and copy files using ms builld commands
Vs 2012 publishing profiles and copy files using ms builld commands
 
Css 選擇器規劃
Css 選擇器規劃Css 選擇器規劃
Css 選擇器規劃
 

Similar to Knockout extender

Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin developmentZarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa
 

Similar to Knockout extender (20)

Dropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudDropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google Cloud
 
-Kotlin_Camp_Unit2.pptx
-Kotlin_Camp_Unit2.pptx-Kotlin_Camp_Unit2.pptx
-Kotlin_Camp_Unit2.pptx
 
-Kotlin Camp Unit2.pptx
-Kotlin Camp Unit2.pptx-Kotlin Camp Unit2.pptx
-Kotlin Camp Unit2.pptx
 
Knative Outro
Knative OutroKnative Outro
Knative Outro
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
Knockoutjs Part 3 Computed Observables
Knockoutjs Part 3 Computed ObservablesKnockoutjs Part 3 Computed Observables
Knockoutjs Part 3 Computed Observables
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin developmentZarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
Zarafa SummerCamp 2012 - Basic Introduction WebApp plugin development
 
Splunk Ninjas: New Features, Pivot, and Search Dojo
Splunk Ninjas: New Features, Pivot, and Search DojoSplunk Ninjas: New Features, Pivot, and Search Dojo
Splunk Ninjas: New Features, Pivot, and Search Dojo
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
SplunkLive! Tampa: Splunk Ninjas: New Features, Pivot, and Search Dojo
SplunkLive! Tampa: Splunk Ninjas: New Features, Pivot, and Search Dojo SplunkLive! Tampa: Splunk Ninjas: New Features, Pivot, and Search Dojo
SplunkLive! Tampa: Splunk Ninjas: New Features, Pivot, and Search Dojo
 
Splunk Ninjas: New Features and Search Dojo
Splunk Ninjas: New Features and Search DojoSplunk Ninjas: New Features and Search Dojo
Splunk Ninjas: New Features and Search Dojo
 
Swift 5.2 what are the new things that you need to know about
Swift 5.2   what are the new things that you need to know aboutSwift 5.2   what are the new things that you need to know about
Swift 5.2 what are the new things that you need to know about
 
Meet the CBO in Version 11g
Meet the CBO in Version 11gMeet the CBO in Version 11g
Meet the CBO in Version 11g
 

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Knockout extender

  • 2. Using extenders to augment observables Knockout observables provide the basic features necessary to support reading/writing values and notifying subscribers when that value changes
  • 3. Using extenders to augment observables How to create an extender Using the ko.extenders object ko.extenders.logChange = function(target, option) { target.subscribe(function(newValue) { console.log(option + ": " + newValue); }); return target; }; this.firstName = ko.observable("Bob").extend({logChange: "first name"});
  • 4. Using extenders to augment observables How to create an extender  View: <p><input data-bind="value: myNumberOne" /> (round to whole number)</p> <p><input data-bind="value: myNumberTwo" /> (round to two decimals)</p>
  • 5. ko.extenders.numeric = function(target, precision) { //create a writeable computed observable to intercept writes to our observable var result = ko.computed({ read: target, //always return the original observables value write: function(newValue) { var current = target(), roundingMultiplier = Math.pow(10, precision), newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue), valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier; //only write if it changed if (valueToWrite !== current) { target(valueToWrite); } else { //if the rounded value is the same, but a different value was written, force a notification for the current field if (newValue !== current) { target.notifySubscribers(valueToWrite); } } } }).extend({ notify: 'always' }); //initialize with current value to make sure it is rounded appropriately result(target()); //return the new computed observable return result; }; function AppViewModel(one, two) { this.myNumberOne = ko.observable(one).extend({ numeric: 0 }); this.myNumberTwo = ko.observable(two).extend({ numeric: 2 }); } ko.applyBindings(new AppViewModel(221.2234, 123.4525));