An idiom for comparing observed knockouts

I have the following problem. I want to check that the element clicked in the table does not match the selected model.selected.

var model= { items: ko.observableArray(), selected : ko.observable() }; <tbody> <!-- ko foreach: model.items --> <tr data-bind="click:$parent.model.set_selected_item"> <td style="cursor:pointer" data-bind="varchar : title"></td> </tr> <!-- /ko --> </tbody> //ID is an observable //selected may not be set yet - ie an empty observable; var set_selected_item = function(item){ //if item is different set model.LandItem_selected(item); do_routine(item) //else //do nothing } 

because the element is observable, it is never equal to zero; how would I check if the observable is not yet installed?

Any help is greatly appreciated.

+4
source share
2 answers

Deploy Observable Before Comparison

 var item1 = ko.observable() console.log(ko.utils.unwrapObservable(item1)) console.log(ko.utils.unwrapObservable(item1) == null) item1(1) console.log(ko.utils.unwrapObservable(item1) == null) 

Exit

undefined

True

falsely

+6
source

You can use the expansion of the observable with parentheses, for example:

 var underlyingValue = item(); 

or, if you are not sure if the variable is observable, you can use this method:

 var underlyingValue = ko.utils.unwrapObservable(item); 

which basically checks if the variable is observable or not, and if it is, it does it first using parentheses.

When you have a base value, you can do what you usually do.

+2
source

Source: https://habr.com/ru/post/1403091/


All Articles