21

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?

2

2 Answers 2

34

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.

2
  • 9
    It is just amazing.. Knockout can process comments.. :) Mar 9, 2016 at 10:05
  • 5
    I've spent half a day to get how page that uses this comment feature works. Extremely confusing for knockout newbies.
    – Zharro
    May 30, 2017 at 12:41
10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.