[英]comparing two observable values in knockout data-bind
在我的淘汰賽應用程序中,我試圖比較兩個可觀察的值並相應地分配類。
但是可觀察值的評估不會改變事件,盡管值在可觀察值中有所變化
下面是代碼
<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>
我看到添加的跨度中的值發生了變化,但表達式值沒有變化。
currentPlan和currentElem都是可觀察的。
請指導
謝謝
什魯蒂·奈爾
如果CurrentPlan
和CurrentElem
是可觀察到的,則需要使用方括號()來獲取值
<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>
我可以看到值在添加的跨度中發生了變化
在那種情況下,我假設Id
和PointPlanId
是可觀察的。
因此,您應該將代碼更改為:
css: {'disabled':CurrentPlan().Id() == CurrentElem().PointPlanId()}"
這是一個工作片段:
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()
,因為敲除會使用ko.utils.unwrapObservable
自動處理可觀察對象和常規屬性。 當您具有某種涉及可觀察對象的值的表達式時,需要使用()
獲取可觀察對象的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.