Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add an element attribute in knockout.js

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

like image 599
maerics Avatar asked Oct 18 '12 20:10

maerics


People also ask

What is $data in Knockout?

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.

What is two way binding in knockout JS?

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.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

What is data bind in knockout JS?

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.


1 Answers

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.

like image 129
JJ Rohrer Avatar answered Sep 22 '22 07:09

JJ Rohrer