Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the check if a value is NULL or unassigned in knockout.js?

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.

like image 213
pcbabu Avatar asked Oct 21 '14 06:10

pcbabu


2 Answers

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.

like image 114
joshmcode Avatar answered Nov 10 '22 22:11

joshmcode


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.

like image 41
Suchit kumar Avatar answered Nov 10 '22 20:11

Suchit kumar