blue-sky
blue-sky

Reputation: 53806

Confused about <!-- ko if: $parent.name == name --> in knockout js

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?

Upvotes: 21

Views: 31620

Answers (2)

Juan Campa
Juan Campa

Reputation: 1231

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.

Upvotes: 10

War10ck
War10ck

Reputation: 12508

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.

Upvotes: 34

Related Questions