Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Knockout to check if undefined

I have a template that I would like to use a different bit of HTML based on the control being used:

<!-- ko if: Value -->
    ........
<!-- /ko -->

<!-- ko ifnot: Value -->
    ........
<!-- /ko -->

The intention of this code is to select the first bit if Value is defined, the second bit if not. However, this always causes a binding error: Value is not defined which I'm fairly sure errors out just checking if the control has Value defined.

Is there a better way to use these if statements to check if a binding is defined or not?

like image 623
tnw Avatar asked Nov 08 '13 16:11

tnw


People also ask

How do you write if condition in knockout?

If the condition evaluates to true or true-like value, then the given HTML markup will be processed. Else, it will be removed from DOM. If the condition in the parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes.

What is Knockout used for?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

Is KnockoutJS easy?

KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects. It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features.

How do you activate knockout?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.


Video Answer


1 Answers

If Value is truly not defined, then you can use $data.Value to avoid the "not defined" errors.

like image 184
RP Niemeyer Avatar answered Oct 27 '22 23:10

RP Niemeyer