How to selectively bind attributes in Knockout
I want to set different data theme attributes based on the state of the model \ object. Here I am just setting 'b' or 'd' for the data-theme attribute (jQuery Mobile). I can get it to work with:
<!-- ko if: $data.id() == $parent.selectedMatchId() -->
<li data-bind="text: $data.date" data-theme="b"></li>
<!-- /ko -->
<!-- ko ifnot: $data.id() == $parent.selectedMatchId() -->
<li data-bind="text: $data.date" data-theme="d"></li>
<!-- /ko -->
which is a little ugly. I thought (hoped) I could use an expression inside a binding attribute, but the knockout binding mechanism doesn't like what I give it.
<li data-bind="text: $data.date,
attr: {'data-theme' : $data.id() == $parent.selectedMatchId() : 'd' ? 'b'}"></li>
Is there a cleaner way to do this than the "ko if" and "ko ifnot" which I am using?
source to share
You can use template binding. With this binding, you can dynamically choose which template to use.
The documentation is here: http://knockoutjs.com/documentation/template-binding.html#note_4_dynamically_choosing_which_template_is_used
source to share
I prefer to use a custom binding that modifies my jquery mobile theme. For example, changing the theme of a button based on a true or false observable value to indicate that the button is selected or not:
Custom binding:
ko.bindingHandlers.jqmButtonTheme = {
init: function (element, valueAccessor)
{
var value = valueAccessor();
ko.utils.unwrapObservable(value) ? $(element).buttonMarkup({ theme: 'b' }) : $(element).buttonMarkup({ theme: 'a' });
},
update: function (element, valueAccessor)
{
var value = valueAccessor();
ko.utils.unwrapObservable(value) ? $(element).buttonMarkup({ theme: 'b' }) : $(element).buttonMarkup({ theme: 'a' });
}
};
JSFiddle example:
source to share