Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 826
blue-sky Avatar asked Jan 29 '13 18:01

blue-sky


People also ask

What is Ko observable in KnockoutJS?

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.

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 two-way binding in KnockoutJS?

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.


2 Answers

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.

like image 76
War10ck Avatar answered Oct 14 '22 21:10

War10ck


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.

like image 27
Juan Campa Avatar answered Oct 14 '22 21:10

Juan Campa