Derik Whittaker

Syndication

News


Knockout JS, Attr Binding and Radio Button Values

When working with Knockout you have the ability to seamlessly bind to a radio buttons via the checked binder.  When working with Radio buttons it is very common to use the value attribute in order to know which radio button was selected.  In fact the code below should be very common if using this binding.

image

However, when I look at the code above I have 1 issue with it and that is the use of the hard coded value “1” as the value.  I HATE magic strings/values.  Having a raw value like this in your code does not lead to discoverability, I mean what what does ”1” mean?  I would much rather use a constant/enumeration here in order to provide better discoverability.  However, you straight up HTML does not lend itself to this.  For example the code below would NOT yield the results you are expecting.

image

However, we can harness the power of Knockouts Attr binding to solve our readability problem.  Take a look at the code below

image

By using the Attr binding I can use the Knockout binding engine to add the value 1 to my HTML at runtime which gives me the correct value as well having my enum value for readability at code time.  Below is the rendered HTML

image

Till next time,

P.S. If you want to learn more about Knockout watch my Pluralsight Course on Knockout JS

P.S.S. If you want to learn how to transition your XAML skills to HTML you can watch my course on Html for the XAML Developer


Posted 07-11-2013 6:13 AM by Derik Whittaker
Filed under:

[Advertisement]

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)