Reputation: 8487
I am using knockout attr binding for data- attributes, like :
<div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }">
</div>
Now what i want is that if any observable varibale i.e. Fire and Age
is null or empty than i do not want to add an empty attribute name. So after applying binding if suppose Age
is empty than i do not want my markup to be :
<div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }" data-age data-fire="Yes">
</div>
Instead i want to remove data-age and want this clean markup :
<div data-bind="attr : { 'data-fire': Fire, 'data-age': Age }" data-fire="Yes">
</div>
Is there any way to achieve this in knockout.js?
Upvotes: 1
Views: 521
Reputation: 5147
You can control this yourself using custom binding:
<div data-bind="addAttributes : { 'data-fire': Fire, 'data-age': Age }"></div>
Then have a handler:
ko.bindingHandlers.yourBindingName = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
}
};
In these methods, you can check the values and add the attributes in manually (using jQuery, for example) only if the values aren't blank.
Upvotes: 1