Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

knockout.js - Output Knockout observable value even if false

I'm using a Knockout observable called this.expanded to both handle whether or not to render some HTML, and also using the value inside an aria-expanded attribute.

<button data-bind="attr: { 'aria-expanded': expanded }">
<!-- ko if : expanded -->
   <div>...</div>
<!-- /ko -->

The problem with using my variable expanded in both cases is that I notice when expanded is false, I don't get the output of aria-expanded attribute at all.

// When expanded is true:
<button aria-expanded="true"></button>

// When expanded is false:
<button></button>

// What I want:
<button aria-expanded="false"></button>

How can I still output the attribute, just with false, when expanded is false?

I tried creating a secondary variable which would check the observable and convert it to a string:

this.expandedStatus = this.expanded().toString()

But I noticed that expandedStatus does not seem to update/observe anymore if used in this way.

question from:https://stackoverflow.com/questions/66049274/output-knockout-observable-value-even-if-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could simply bind the aria-expanded attribute to the toString() value of the observable without introducing a new observable. Have a look at the example below:

function Test() {
  var self = this;
  self.expanded = ko.observable(false);
  self.toggleExpanded = function() {
    self.expanded(!self.expanded());
  }
}

ko.applyBindings(new Test());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button data-bind="attr: { 'aria-expanded': expanded().toString() }">
<!-- ko if : expanded -->
   <span>...</span>
<!-- /ko -->
</button>

<p>
  <button data-bind="click: toggleExpanded">Toggle</button>
</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...