Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout binding how to remove an attribute

Tags:

knockout.js

Let's say I have an Html element

<element testattribute='a'></element>

I know I can pass the value of testattribute using a binding like this:

<element data-bind="attr: { testattribute: 'a'}></element>

But how can I completely remove this attribute through the binding. So if the original value was

 <element testattribute: 'a'></element>

my end result should be

<element></element>
like image 219
dreamerkumar Avatar asked May 21 '13 12:05

dreamerkumar


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.

What is applyBindings in Knockout?

To apply bindings for the whole HTML document, it can be done using the Knockout function applyBindings() with passing the view model as the first and the only parameter: ko. applyBindings(viewModel); To apply Knockout for a part of the HTML document, pass the DOM element as a second parameter: ko.

Can we have multiple Knockout models on a single page?

Knockout now supports multiple model binding. The ko. applyBindings() method takes an optional parameter - the element and its descendants to which the binding will be activated. This restricts the activation to the element with ID someElementId and its descendants.

What is Ko observable?

An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.


2 Answers

The attr binding in KO will actually remove the attribute if the value is false, null, or undefined. So, if you bind against an observable and then set it to one of those values (not empty string), then the attribute will be removed.

like image 167
RP Niemeyer Avatar answered Oct 01 '22 18:10

RP Niemeyer


you should do this ternary inline because form not accepts several checked radio button and it will ignore the knockout comments so none would be checked to avoid do like:

<input type="radio" data-bind="attr:{'checked':($data.amount > 0) ? 'checked' : false}" id="q156" name="foo" value="positive" />

this will set accurate!

like image 35
john Smith Avatar answered Oct 01 '22 17:10

john Smith