How can I check if a value is null or unassigned in knockout.js?

Suppose in this example it is firstName

not set, but a lastName

value is assigned. How to check if a value is assigned or not.

function AppViewModel() {
    this.firstName = ko.observable();
    this.lastName = ko.observable('Smith');
}

      

Which one is the best approach? Will this work?

   if(lastName  == '')
       //do something

      

or

   if(lastName)
       //do something

      

or

   if(lastName  == null)
       //do something

      

Please, help.

+3


source to share


2 answers


you can check how:

if(lastName  != undefined  && lastName().length > 0 ){

// do something else.
}

      



Edit: you have to call lastName

as a function because the observable should read the current value.

+3


source


I know the OP's question / example was in JavaScript, but I stumbled upon this question because of the title:

How can I check if a value is null or unassigned in knockout.js?

This can also be verified in the view very simply: (example from knockout code example here ):



<div data-bind="if: capital">
      Capital: <b data-bind="text: capital.cityName"> </b>
 </div>

      

This example has an object called capital and the operator if

checks for null by default. If "Capital" is not null, the second line is executed, otherwise it skips it. This works very well for simple cases.

+3


source







All Articles