简体   繁体   中英

knockoutjs: How to use boolean && in if condition?

I'm developing knockoutjs, I want to use boolean in data-bind and here my code but it is not working

<p class="cmt-post" data-bind="if:deleteDate&&owner='1'">
     <span data-bind="text:deleteDate">
     </span>
 </p>

If deleteDate and owner are observables you need to evaluate them using () . Also you should use === instead of = as === is used to compare equality and will also ensure that the types are the same. Ie 1 === '1' will false whereas 1 == '1' is true.

<p class="cmt-post" data-bind="if:deleteDate()&&owner()==='1'">
     <span data-bind="text:deleteDate">
     </span>
</p>

您需要使用double equals来比较相等性(就像您在标准JS中所做的那样,否则是一个赋值):

 data-bind="if:deleteDate && owner == '1'">

You are assigning owner value use == instead of =

<p class="cmt-post" data-bind="if:deleteDate&&owner == '1'">
   <span data-bind="text:deleteDate"></span>

I would propose You to separate any logic to a viewModel instead

So consider method in your view model for example:

function ViewModel(){

  this.delete_date_visible = ko.pureComputed(
      this.getDeleteDateVisible,
      this
  )
};

ViewModel.prototype.getDeleteDateVisible = function(){
   return this.deleteDate() && this.owner == '1'
}

In the view:

<span data-bind="if: delete_date_visible">...</span>

or even

<!-- ko if: delete_date_visible -->
<span>...</span>
<!-- /ko -->

which looks cleaner i think.

The pure computed that is using view model's method because:

  • you don't need to call it in the template
  • the getter method could be re-used natively in the view model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM