I've encountered this Knockout code and I'm confused about what the below code is performing:
<!-- ko if: $parent.name == name -->
<a data-bind='text: name'></a>
<!-- /ko -->
Shouldn't this code be interpreted as a comment?
Reading the documentation:
http://knockoutjs.com/documentation/custom-bindings-for-virtual-elements.html
this looks like a custom binding?
Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the 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 $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.
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.
It's a knockout conditional comment. The HTML inside the comment block is only executed if the code validates to true. Knockout can read and process this comment for you. You don't have to do anything special. Simply supply the conditional and make sure the variables you reference do in fact exist. Then sit back and let knockout do the rest.
It's not a custom binding. What you encountered is what knockout's documentation calls a "Virtual Element", it's a binding applied to a piece of code instead of an element. If you want to conditionally evaluate (i.e. bind to your viewmodel) a part of the DOM you can either put it inside a div with an if
binding or put it inside comments like those.
HTML comments are part of the DOM so there's nothing stopping knockout from retrieving and interpreting them.
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