how to use if in a function in knockout js?

2019-03-05 05:45发布

i have a condition in my function . i want to set a value of a variable true or false on the basis of another variable whether it is empty of not in knockout js?

 self.editData = function (data) { 
     self.id(data.id());
     self.nscto(data.nscto());
     if (nscto != null && "".equals(nscto)){
         self.view(true)
     }
 }

here i write if condition as we use in java language i want to use this scenarion in knockout how can i do it ?

3条回答
Viruses.
2楼-- · 2019-03-05 05:48

The way you have it written you would need

self.editData = function (data) { 
   self.id(data.id);
   self.nscto(data.nscto);
   if (self.nscto() != null && self.nscto() == ""){
        self.view(true);
   }
}
查看更多
【Aperson】
3楼-- · 2019-03-05 05:55

There are many ways to do what you want:

if ( null != self.nscto() && "" === self.nscto() )
{
    self.view(true)
}    

or

if ( null != self.nscto() && self.nscto().length === 0 )
{
    self.view(true)
}

or simpler

self.view( null != self.nscto() && "" === self.nscto() )
查看更多
乱世女痞
4楼-- · 2019-03-05 06:14

You have used two different variables (nsct and nsc) and an operator that doesn't exist (=!). The last part of the condition would be interpreted as an assignment: nsc = (!"").

Also, the logic is wrong, there is no value that is null and an empty string at the same time, so the condition would always be true. You would use the && operator instead:

if (nsct != null && nsct != "") {
  self.view(true);
}

If you want to set it to false if the condition isn't true, then you would use an else also:

if (nsct != null && nsct != "") {
  self.view(true);
} else {
  self.view(false);
}

You can also do that by using the value of the condition:

self.view(nsct != null && nsct != "");
查看更多
登录 后发表回答