Suppose in this example, firstName
is not set and lastName
is assigned a value. How to check if the value is assigned or not.
function AppViewModel() {
this.firstName = ko.observable();
this.lastName = ko.observable('Smith');
}
Which one is the best approach? Will these work?
if(lastName == '')
//do something
or
if(lastName)
//do something
or
if(lastName == null)
//do something
Please help.
I know the OP's question/example was in JavaScript, but I stumbled on this question because of the title:
How to check if a value is NULL or unassigned in knockout.js?
This can ALSO be checked in the view, very simply: (example is from Knockout's example code here):
<div data-bind="if: capital">
Capital: <b data-bind="text: capital.cityName"> </b>
</div>
In this example there is an object called capital and the if
statement checks for null by default. If Capital is not null, then the second line is executed, otherwise it skips it. This works really well for simple cases.
you can check like:
if(lastName != undefined && lastName().length > 0 ){
// do something else.
}
Edit: You have to invoke lastName
as a function because it is an observable to read its current value.
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