【问题标题】:comparing two observable values in knockout data-bind比较敲除数据绑定中的两个可观察值
【发布时间】:2019-06-14 14:36:12
【问题描述】:

在我的淘汰赛申请中,我试图比较两个可观察值并相应地分配类。

但是 observable 的评估不会改变事件,尽管值在 observable 中发生了变化

下面是代码

<div class="col-lg-4 col-sm-4 col-xs-4 text-center">
      <span data-bind="text:CurrentPlan().Id "></span>
      <span data-bind="text:CurrentElem().PointPlanId "></span>
      <span data-bind="text:CurrentPlan.Id == CurrentElem.PointPlanId"></span>
      <button class="btn btn-blue btn-alt" type="button" data-bind="click:AssignPlan,
         css: {'disabled':CurrentPlan.Id == CurrentElem.PointPlanId}"> Assign </button>
</div>

我可以看到添加的 span 中的值发生了变化,但表达式值没有变化。

currentPlan 和 currentElem 都是 observables。

请指导

谢谢

Shruti nair

【问题讨论】:

  • 您忘记了获取可观察值所需的()。试试CurrentPlan().Id == CurrentElem().PointPlanId
  • 即使值相同,也无法将其评估为 false。
  • 如果解决了您的问题,请mark the answer as accepted

标签: javascript knockout.js observable


【解决方案1】:

如果CurrentPlanCurrentElem 是可观察的,那么您需要使用方括号() 来获取值

<div class="col-lg-4 col-sm-4 col-xs-4 text-center">
      <span data-bind="text:CurrentPlan().Id "></span>
      <span data-bind="text:CurrentElem().PointPlanId "></span>
      <span data-bind="text:(CurrentPlan().Id == CurrentElem().PointPlanId)"></span>
      <button class="btn btn-blue btn-alt" type="button" data-bind="click:AssignPlan,
         css: {'disabled':(CurrentPlan().Id == CurrentElem().PointPlanId)}"> Assign </button>
</div>

【讨论】:

  • 假设 CurrentElem 和 CurrentPlan 的值都是 45,表达式 CurrentPlan().Id==CurrentElem().PointPlanId 的计算结果为 false,即使在值更新后也不会改变
  • 你介意展示你的JS代码吗?特别是值的更新方式
【解决方案2】:

我可以看到添加的跨度中的值发生变化

在这种情况下,我假设 IdPointPlanId 是可观察的。

因此,您应该将代码更改为:

css: {'disabled':CurrentPlan().Id() == CurrentElem().PointPlanId()}"

这是一个有效的 sn-p:

var viewModel = function() {
  const self = this;

  self.CurrentPlan = ko.observable({
    Id: ko.observable(10)
  });
  
  self.CurrentElem = ko.observable({
    PointPlanId: ko.observable(20)
  });

  self.AssignPlan = () => {}
  
  // make the value equal after 3 seconds
  setTimeout(() => self.CurrentPlan().Id(20), 3000);
}

ko.applyBindings(new viewModel())
.disabled {
  color: grey
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="col-lg-4 col-sm-4 col-xs-4 text-center">
  <span data-bind="text:CurrentPlan().Id"></span>
  <span data-bind="text:CurrentElem().PointPlanId"></span>
  <span data-bind="text:CurrentPlan().Id() === CurrentElem().PointPlanId()"></span>
  <button class="btn btn-blue btn-alt" type="button" data-bind="click:AssignPlan,
         css: {'disabled':CurrentPlan().Id() === CurrentElem().PointPlanId()}">Assign</button>
</div>

您不必在第一个text 绑定中使用CurrentPlan().Id(),因为knockout 会使用ko.utils.unwrapObservable 自动处理可观察对象和常规属性。当您有某种涉及可观察对象值的表达式时,您需要使用() 来获取可观察对象的值。

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 2011-12-12
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多