The knockout.js library has an "attr"
data binding which allows you to dynamically change the value of an HTML element attribute (e.g. the "title"). However, in some cases, the attribute may or may not be needed depending on the corresponding observable on the bound object. For example, if my model has a "title" observable I might want to set the "title" attribute if it is present (non-null) or skip the attribute entirely if it is not present (null).
Does knockout provide any way to conditionally set an attribute? (Ideally without conditionally rendering the entire element opening tag...)
[Note] This similarly named question was actually resolved by knockout's special handling of CSS classes and does not relate to this question (or its own title): How to conditionally render an css class with knockoutjs
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel. folders array.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.
I needed this when selecting an <option>
(that I was generating manually instead of built-in knockout).
<option data-bind="text: text, attr:{ value:value, 'selected': typeof(selected) !== 'undefined' ? selected : null }"> Choice X </option>
This says to always update the 'text' attribute and to add the 'value' attribute, but only add 'selected' if the the data already has a value of 'selected' defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With